2017-10-10 95 views
1

匹配多個列的模式我正好有下列數據框:複製的列值熊貓

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)。

例如: 行0Prod1的值,因此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  

我思考嵌套行/列的循環,但我仍然不足夠的大熊貓熟悉去解決。 非常感謝您的任何建議!

+0

您正在尋找這樣的事情:([基於在熊貓數據幀其他列的值列之間的運動行值] https://stackoverflow.com/questions/15997430/moving-row-values-columns-columns-based-on-other-column-values-in-a-pandas-dataf)? – RoyaumeIX

+0

我在研究現有答案的過程中看到了這一點,但我無法將其應用到我的案例中(可能是因爲我目前的技能) - 我現在在看溫的回覆。 –

回答

3

我打破步驟:

df[['String1', 'String2', 'String3']]=(df[['Prod1', 'Prod2', 'Prod3']]!='') 
df1=df[['String1', 'String2', 'String3']].replace({False:np.nan}).stack().to_frame() 
df1[0]=df[['X1','X2']].replace({'':np.nan}).stack().values 
df[['String1', 'String2', 'String3']]=df1[0].unstack() 
df.replace({None:''}) 


Out[1036]: 
    Prod1 Prod2 Prod3 String1 String2 String3 X1 X2 
0 10     x1     x1  
1   5     x2   x2  
2 10  5   x3  y1   x3 y1 
3     8      x4 x4  
4     8      x5 x5  
5   5  8    x6  y2 x6 y2 
+0

非常感謝您使用'stack()'和'unstack()'。 –

+0

@DavideBarranca Yw〜晚安 – Wen

+1

請注意,爲了我大熊貓的理解,爲什麼在第2行省略第一個'.to_frame()'會導致'[x1,x2,x3, y1,x4,x5,x6,y2]'放入'df1'第一行?那麼,是否有辦法修改第3行的賦值,使其無論如何不用將'df1'轉換爲DataFrame?清楚的是,你的解決方案就像一個魅力,我正在玩你的代碼來學習。謝謝! –