Python Pandas仅合并某些列 [英] Python Pandas merge only certain columns

查看:93
本文介绍了Python Pandas仅合并某些列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以仅合并某些列?我有一个DataFrame df1,其中包含x,y,z和df2列,其中x,a,b,c,d,e,f等.

Is it possible to only merge some columns? I have a DataFrame df1 with columns x, y, z, and df2 with columns x, a ,b, c, d, e, f, etc.

我想合并x上的两个DataFrame,但是我只想合并df2.a,df2.b列-而不是整个DataFrame.

I want to merge the two DataFrames on x, but I only want to merge columns df2.a, df2.b - not the entire DataFrame.

结果将是具有x,y,z,a,b的DataFrame.

The result would be a DataFrame with x, y, z, a, b.

我可以合并然后删除不需要的列,但是似乎有更好的方法.

I could merge then delete the unwanted columns, but it seems like there is a better method.

推荐答案

您可以合并sub-DataFrame(仅包含这些列):

You could merge the sub-DataFrame (with just those columns):

df2[list('xab')]  # df2 but only with columns x, a, and b

df1.merge(df2[list('xab')])

这篇关于Python Pandas仅合并某些列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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