大 pandas 根据联接将列从一个数据框添加到另一个数据框 [英] Pandas add column from one dataframe to another based on a join

查看:80
本文介绍了大 pandas 根据联接将列从一个数据框添加到另一个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有2个数据帧.我想基于列查找将数据框1的列添加到数据框2.如果无法进行联接,则需要在额外的列中使用某个常数(以便可以对此进行过滤).

Assume I have 2 dataframes. I want to add a column of dataframe 1 to dataframe 2 based on a column lookup. If the join is not possible, I want in the extra column a certain constant (so I can filter for that).

图形方式:

代码:

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)

推荐答案

使用 join


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

这篇关于大 pandas 根据联接将列从一个数据框添加到另一个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆