【问题标题】:Merge 2 data frames using values of column vector from dataframe with and column of list from another dataframe使用来自数据帧的列向量值和来自另一个数据帧的列表列合并 2 个数据帧
【发布时间】:2020-10-12 11:52:21
【问题描述】:

假设我有两个数据框,

df1.head()
AH1
A
B
C
D
F

第二个数据框df2.head()

AH1 BC
A,B SAP
C,D XY
A,B,C   BMZ
A,F Zoom

我需要基于相同的值合并两个数据框df1df2 中的列AH1。最后,我的目标是拥有这样的东西,

output
    AH1 BC
    A   SAP, BMZ,Zoom
    B   SAP,BMZ
    C   XY,BMZ
    D   XY
    F   Zoom

感谢任何帮助或建议。我知道pandas.merge 不会出现在列向量和列表列之间。

【问题讨论】:

    标签: python pandas dataframe merge


    【解决方案1】:

    你可以做一个explode:

    (df2.assign(AH1=df2.AH1.str.split(','))
        .explode('AH1')
        .groupby('AH1')
        ['BC'].agg(list)
    )
    

    输出:

    AH1
    A    [SAP, BMZ, Zoom]
    B          [SAP, BMZ]
    C           [XY, BMZ]
    D                [XY]
    F              [Zoom]
    Name: BC, dtype: object
    

    或者用agg(', '.join)替换agg(list)

    (df2.assign(AH1=df2.AH1.str.split(','))
        .explode('AH1')
        .groupby('AH1')
        ['BC'].agg(', '.join)
    )
    

    输出:

    AH1
    A    SAP, BMZ, Zoom
    B          SAP, BMZ
    C           XY, BMZ
    D                XY
    F              Zoom
    Name: BC, dtype: object
    

    【讨论】:

    • 感谢您的解决方案!我会尝试。 AttributeError: 'DataFrame' object has no attribute 'explode'
    • 更新了python版本,它有帮助!谢谢
    猜你喜欢
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2019-07-10
    相关资源
    最近更新 更多