【问题标题】:Combination of two DataFrames with condition两个 DataFrame 与条件的组合
【发布时间】:2023-04-06 06:16:01
【问题描述】:

我需要组合两个数据帧的列(具有非常多的条目),以便第一个 DF 的一列是另一列的索引。

为了解释,这里是一些示例代码

df1 = pd.DataFrame({'ID': ['ID1', 'ID2', 'ID3', 'ID4'],
'Feature': ['Feature1', 'Feature2', 'Feature3', 'Feature2'],
},index=[0, 1, 2, 3])

df2 = pd.DataFrame({'Feature': ['Feature1', 'Feature2', 'Feature3'],
'Property1': ['Property11', 'Property12', 'Property13'],
'Property2': ['Property21', 'Property22', 'Property23']},index=[0, 1, 2])
df2.set_index('Feature', inplace=True)

我希望输出是这样的

    ID   Feature    Property1    Property2
0   ID1  Feature1   Property11   Property21
1   ID2  Feature2   Property12   Property22
2   ID3  Feature3   Property13   Property23
3   ID4  Feature2   Property11   Property22

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    一个简单的合并

    df1.merge(df2, left_on='Feature', right_index=True)
    
    Out[264]:
        ID   Feature   Property1   Property2
    0  ID1  Feature1  Property11  Property21
    1  ID2  Feature2  Property12  Property22
    3  ID4  Feature2  Property12  Property22
    2  ID3  Feature3  Property13  Property23
    

    【讨论】:

      【解决方案2】:

      将另一个数据框的索引设置为要加入的列,然后重置索引:

      df_result = df2.join(df1.set_index('Feature')).reset_index()
      

      【讨论】:

        猜你喜欢
        • 2019-10-02
        • 1970-01-01
        • 1970-01-01
        • 2015-07-11
        • 1970-01-01
        • 2014-09-19
        • 2016-10-24
        • 1970-01-01
        • 2023-02-07
        相关资源
        最近更新 更多