熊猫:合并两个数据框并动态扩展行

时间:2018-09-26 08:59:12

标签: python pandas dataframe

我已经设置了以下数据框

A

[ClaimantId], [ClaimId], [LenderId], [IsWorked] 1 1 1 1 1 2 4 0 1 3 3 1 2 6 1 1

B

[ClaimantId], [Forename], [Surname]
1             Bruce       Wayne
2             Peter       Parker

我想要的输出为

[ClaimantId], [Forename], [Surname], [C1], [C2], [C3], [L1], [L2], [L3], [W1], [W2], [W3]
1             Bruce       Wayne      1      2     3    1     4     3      1    0     1
2             Peter       Parker     6      Nan   Nan  1     Nan   Nan    1    Nan   Nan

我不确定该如何应用,C / L / W列数的上限为20,并且永远不会超过。

非常感谢您的帮助。

谢谢

1 个答案:

答案 0 :(得分:1)

使用:

d = {'ClaimId':'C', 'LenderId':'L','IsWorked':'W'}
df = (A.rename(columns=d)
       .set_index(['ClaimantId',A.groupby('ClaimantId').cumcount()])
       .unstack())
df.columns = [f'{i}{j+1}' for i, j in df.columns]
print (df)
               C1   C2   C3   L1   L2   L3   W1   W2   W3
ClaimantId                                             
1             1.0  2.0  3.0  1.0  4.0  3.0  1.0  0.0  1.0
2             6.0  NaN  NaN  1.0  NaN  NaN  1.0  NaN  NaN

df1 = B.join(df, on='ClaimantId')
print (df1)
    ClaimantId    Forename   Surname   C1   C2   C3   L1   L2   L3   W1   W2  \
0             1      Bruce     Wayne  1.0  2.0  3.0  1.0  4.0  3.0  1.0  0.0   
1             2      Peter    Parker  6.0  NaN  NaN  1.0  NaN  NaN  1.0  NaN   

    W3  
0  1.0  
1  NaN

说明

  1. 字典中的前rename
  2. 然后由set_index创建的计数器Series cumcount
  3. unstack重塑
  4. list comprehensionf-string s一起平铺MultiIndex列
  5. 最后joinDataFrame

编辑:

如果需要相同的长度,则所有列将由MultiIndex创建的新range使用reindex

d = {'ClaimId':'C', 'LenderId':'L','IsWorked':'W'}
df = (A.rename(columns=d)
       .set_index(['ClaimantId',A.groupby('ClaimantId').cumcount()])
       .unstack())

mux = pd.MultiIndex.from_product([df.columns.get_level_values(0).unique(), range(5)])
df = df.reindex(columns=mux, fill_value=0)
df.columns = [f'{i}{j+1}' for i, j in df.columns]
print (df)
             C1   C2   C3  C4  C5   L1   L2   L3  L4  L5   W1   W2   W3  W4  \
ClaimantId                                                                    
1           1.0  2.0  3.0   0   0  1.0  4.0  3.0   0   0  1.0  0.0  1.0   0   
2           6.0  NaN  NaN   0   0  1.0  NaN  NaN   0   0  1.0  NaN  NaN   0   

            W5  
ClaimantId      
1            0  
2            0