匹配多個列的模式我正好有下列數據框:複製的列值熊貓
import pandas as pd
import numpy as np
df = pd.DataFrame({ 'Prod1': ['10','','10','','',''],
'Prod2': ['','5','5','','','5'],
'Prod3': ['','','','8','8','8'],
'String1': ['','','','','',''],
'String2': ['','','','','',''],
'String3': ['','','','','',''],
'X1': ['x1','x2','x3','x4','x5','x6'],
'X2': ['','','y1','','','y2']
})
print(df)
Prod1 Prod2 Prod3 String1 String2 String3 X1 X2
0 10 x1
1 5 x2
2 10 5 x3 y1
3 8 x4
4 8 x5
5 5 8 x6 y2
這是一個與相關聯的弦產品的示意圖表;實際的字符串在列中(X1
,X2
),但根據相應產品是否具有值,它們最終應移至(String1
,String2
,String3
)。
例如: 行0
對Prod1
的值,因此x1
應該搬到String1
。 行1
的值爲Prod2
,因此x2
應移至String2
。
在實際的數據集中,大多數每個Prod
都有一個String
,但在Prods中有多行可以找到多個值,並且應該填充字符串列以優先考慮左側。最終的結果應該是這樣的:
Prod1 Prod2 Prod3 String1 String2 String3 X1 X2
0 10 x1
1 5 x2
2 10 5 x3 y1
3 8 x4
4 8 x5
5 5 8 x6 y1
我思考嵌套行/列的循環,但我仍然不足夠的大熊貓熟悉去解決。 非常感謝您的任何建議!
您正在尋找這樣的事情:([基於在熊貓數據幀其他列的值列之間的運動行值] https://stackoverflow.com/questions/15997430/moving-row-values-columns-columns-based-on-other-column-values-in-a-pandas-dataf)? – RoyaumeIX
我在研究現有答案的過程中看到了這一點,但我無法將其應用到我的案例中(可能是因爲我目前的技能) - 我現在在看溫的回覆。 –