首页 文章

根据匹配的列标签将行值添加到数据框中

提问于
浏览
0

我试着解决这个问题 . 我有三个数据帧,我想根据第三个数据框中的值合并(连接?)其中两个数据帧 . 以下是数据帧:

DF1:

index,fields,a1,a2,a3,a4,a5
2018-06-01,price,1.1,2.1,3.1,4.1,5.1
2018-06-01,amount,15,25,35,45,55
2018-06-02,price,1.2,2.2,3.2,4.2,5.2
2018-06-02,amount,16,26,36,46,56
2018-06-03,price,1.3,2.3,3.3,4.3,5.3
2018-06-03,amount,17,27,37,47,57

DF2:

index,fields,b1,b2,b3
2018-06-01,clients,1,2,3
2018-06-02,clients,1,2,3
2018-06-03,clients,1,2,3

df1和df2中的列不同,但它们的关系是df3 .

DF3:

index,product1,product2
0,a1,b1
1,a2,b1
2,a3,b2
3,a4,b2
4,a5,b3

我想合并df1和df2中的数据,但保留与d1中相同的列(因为b1,b2,b3用a1,a2,a3,a4和a5引用) . 这是df4,我想要的理想数据帧 .

DF4:

index,fields,a1,a2,a3,a4,a5
 2018-06-01,price,1.1,2.1,3.1,4.1,5.1
 2018-06-01,amount,15,25,35,45,55
 2018-06-01,clients,1,1,2,2,3
 2018-06-02,price,1.2,2.2,3.2,4.2,5.2
 2018-06-02,amount,16,26,36,46,56
 2018-06-02,clients,4,4,5,5,6
 2018-06-03,price,1.3,2.3,3.3,4.3,5.3
 2018-06-03,amount,17,27,37,47,57
 2018-06-03,clients,7,7,8,8,9

提前谢谢了,

2 回答

  • 1

    Unpivot df2 使用df.melt

    df2_melt = df2.melt(["index", "fields"], var_name="product2")
    

    从参考表 df3 删除冗余列 index ,使用 melted df2 删除pd.merge

    merged = pd.merge(df2_melt, df3.drop("index", axis=1), on="product2")\
        .drop("product2", axis=1)
    

    从合并结果中做pd.pivot_table

    new_rows = pd.pivot_table(merged, index=["index", "fields"],
                              columns="product1", values="value")\
        .reset_index()
    

    使用pd.concatdf1 添加新行,对行进行排序并重置索引:

    pd.concat([df1, new_rows]).sort_values("index").reset_index(drop=True)
    

    Result

    product1    index       fields  a1      a2      a3      a4      a5
    0           2018-06-01  price   1.1     2.1     3.1     4.1     5.1
    1           2018-06-01  amount  15.0    25.0    35.0    45.0    55.0
    2           2018-06-01  clients 1.0     1.0     2.0     2.0     3.0
    3           2018-06-02  price   1.2     2.2     3.2     4.2     5.2
    4           2018-06-02  amount  16.0    26.0    36.0    46.0    56.0
    5           2018-06-02  clients 1.0     1.0     2.0     2.0     3.0
    6           2018-06-03  price   1.3     2.3     3.3     4.3     5.3
    7           2018-06-03  amount  17.0    27.0    37.0    47.0    57.0
    8           2018-06-03  clients 1.0     1.0     2.0     2.0     3.0
    
  • 0

    如果你重命名df2的列:

    df2 = df2.rename(colunmns={'b1':'a1', 'b2':'a2', 'b3':'a3'})
    

    然后你可以做一个简单的concat:

    fields = [df1, df2]
    df4 = pd.concat(fields)
    

    你得到了所需的df4

    但是在df2中,只有a1-a3,而在df4中有列a1-a5,所以df2的行将为a4,a5设置NaN,除非你以某种方式创建它们的列 . 你可以这样做:

    df2['a4'] = df2['a1']
    

    ......等

相关问题