繁体   English   中英

pandas:将列附加到 df,这是另一个 df 的 prat

[英]pandas : appending columns to df that is prat of another df

我有 2 个 pandas 数据帧:

df1:

c1 c2 X
1个 1个 1个
2个 1个 4个
1个 2个 1个
2个 2个 4个

和 df2:

c1 c2 c3
1个 1个 1个
1个 2个 1个
2个 2个 2个

我想 append x行到df2像:

c1 c2 c3 X
1个 1个 1个 1个
1个 2个 1个 1个
2个 2个 2个 4个

我尝试使用join ,但因为我没有唯一索引,所以它不起作用:

df1.set_index(['c1', 'c2'], inplace=True)
df2.set_index(['c1', 'c2'], inplace=True,drop=False)
df2=df2.join(df1)

df2:

c1 c2 c3 X
1个 1个 1个
1个 2个 1个
2个 2个 2个

也许做你的问题所问的最简单的方法是这样的:

df2 = pd.merge(df2, df1, on=['c1', 'c2'])

我们在数据帧 df1 和 df2 的c1c2列上进行了“内部”连接(pandas.merge() 的默认值)。

或者,这是一种使用 DataFrame.join() 获得指定结果的方法,其方法类似于您根据问题尝试过的方法:

df2 = df2.set_index(['c1', 'c2']).join(df1.set_index(['c1', 'c2'])).reset_index()

结果:

   c1  c2  c3  x
0   1   1   1  1
1   1   2   1  1
2   2   2   2  4

请注意, inplace已被删除,因为通常不鼓励使用它,我们现在提前 go 并允许 df2 的 c1 和 c2 列被 set_index() 删除,稍后使用 reset_index() 来恢复它们。

暂无
暂无

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

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