[英]append columns of a data frame to a different data frame in pandas
Given these two pandas data frames: 给定这两个熊猫数据帧:
>>> df1 = pd.DataFrame({'c1':['a','b','c','d'], 'c':['x','y','y','x']})
c1 c2
0 a x
1 b y
2 c y
3 d x
>>> df2 = pd.DataFrame({'c1':['d','c','a','b'], 'val1':[12,31,14,34], 'val2':[0,0,1,1]})
c1 val1 val2
0 d 12 4
1 c 31 3
2 a 14 1
3 b 34 2
I'd like to append the columns val1
and val2
of df2
to the data frame df1
, taking into account the elements in c1
. 考虑到
c1
的元素,我想将df2
val1
和val2
列附加到数据帧df1
中。 The updated df1
would then look like: 更新后的
df1
如下所示:
>>> df1
c1 c2 val1 val2
0 a x 14 1
1 b y 34 2
2 c y 31 3
3 d x 12 4
I thought of using a combination of set_index and update: df1.set_index('c1').update(df2.set_index('c1'))
, but it didn't work... 我想过使用set_index和update的组合:
df1.set_index('c1').update(df2.set_index('c1'))
,但是没有用...
You could use pd.merge
: 您可以使用
pd.merge
:
import pandas as pd
df1 = pd.DataFrame({'c1':['a','b','c','d'], 'c2':['x','y','y','x']})
df2 = pd.DataFrame({'c1':['d','c','a','b'], 'val1':[12,31,14,34], 'val2':[4,3,1,2]})
df1 = pd.merge(df1, df2, on=['c1'])
print(df1)
yields 产量
c1 c2 val1 val2
0 a x 14 1
1 b y 34 2
2 c y 31 3
3 d x 12 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.