繁体   English   中英

Pandas基于连接将列从一个数据帧添加到另一个数据帧

[英]Pandas add column from one dataframe to another based on a join

假设我有2个数据帧。 我想基于列查找向数据帧2添加一列数据帧1。 如果连接不可能,我想在额外的列中有一个常量(所以我可以对其进行过滤)。

图形:

在此输入图像描述

码:

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)

使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM