【问题标题】:Pandas add column from one dataframe to another based on a joinPandas 基于连接将列从一个数据帧添加到另一个数据帧
【发布时间】:2018-02-23 00:24:00
【问题描述】:

假设我有 2 个数据框。我想根据列查找将一列数据框 1 添加到数据框 2。如果无法连接,我希望在额外的列中有一个特定的常量(所以我可以过滤)。

图形化:

代码:

import pandas as pd
import numpy as np

data = np.array([['','Col1','Col2'],
                ['Row1','2','TWO'],
                ['Row2','1','ONE']]
            )

data2 = np.array([['','Col3','Col4'],
                ['Row1','1','T1'],
                ['Row2','2','T2'],
                ['Row3','3','T3']]
            )

df = pd.DataFrame(data=data[1:,1:],
                  index=data[1:,0],
                  columns=data[0,1:])

df2 = pd.DataFrame(data=data2[1:,1:],
                  index=data2[1:,0],
                  columns=data2[0,1:])

result_df = df2 + join Col2 based on df2.Col3 = df.Col1. Add certain string constant if join fails. 

print(df)
print(df2)
print(result_df)

【问题讨论】:

    标签: python pandas join dataframe


    【解决方案1】:

    你也可以尝试使用pd.merge():

    df3 = pd.merge(df2, df[['Col1','Col2']], left_on='Col3', right_on='Col1', how='left')
    

    【讨论】:

      【解决方案2】:

      使用joinmap

      df = df2.join(df.set_index('Col1'), on='Col3')
      print (df)
           Col3 Col4 Col2
      Row1    1   T1  ONE
      Row2    2   T2  TWO
      Row3    3   T3  NaN
      

      df2['Col2'] = df2['Col3'].map(df.set_index('Col1')['Col2'])
      print (df2)
           Col3 Col4 Col2
      Row1    1   T1  ONE
      Row2    2   T2  TWO
      Row3    3   T3  NaN
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-09
        • 2022-10-12
        • 2021-05-27
        • 1970-01-01
        • 1970-01-01
        • 2015-09-08
        相关资源
        最近更新 更多