我的第一个数据框是这样的:
RowCol Value_Pre
Key1 234
Key3 235
Key2 235
Key4 237
我的第二个数据框是:
RowCol Value_Post
Key3 235
Key1 334
Key4 237
Key2 435
如何通过组合两个数据帧来创建第三个数据帧(如下所示)
RowCol Value_Pre Value_Post
Key1 234 334
Key3 235 235
Key2 235 435
Key4 237 237
如何用 Python 开发此代码?
最佳答案
使用map
:
df1['Value_Post'] = df1['RowCol'].map(df2.set_index('RowCol')['Value_Post'])
print (df1)
RowCol Value_Pre Value_Post
0 Key1 234 334
1 Key3 235 235
2 Key2 235 435
3 Key4 237 237
或者merge
使用左连接,特别是在必要时附加多个新列:
df = df1.merge(df2, on='RowCol', how='left')
关于python - 如何根据 Pandas 中第一个数据帧中的某些列值添加第二个数据帧中的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52966472/