两个pandas数据框中共有的列的列表 [英] list of columns in common in two pandas dataframes

查看:90
本文介绍了两个pandas数据框中共有的列的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑对每个具有大量列的数据帧进行合并操作.不想结果有两个具有相同名称的列.我正在尝试查看两个框架之间共有的列名列表:

I'm considering merge operations on dataframes each with a large number of columns. Don't want the result to have two columns with the same name. Am trying to view a list of column names in common between the two frames:

import pandas as pd

a = [{'A': 3, 'B': 5, 'C': 3, 'D': 2},{'A': 2,  'B': 4, 'C': 3, 'D': 9}]
df1 = pd.DataFrame(a)
b = [{'F': 0,  'M': 4,  'B': 2,  'C': 8 },{'F': 2,  'M': 4, 'B': 3, 'C': 9}]
df2 = pd.DataFrame(b)

df1.columns
>> Index(['A', 'B', 'C', 'D'], dtype='object')
df2.columns
>> Index(['B', 'C', 'F', 'M'], dtype='object')

(df2.columns).isin(df1.columns)
>> array([ True,  True, False, False])

我该如何对Index对象上的NumPy布尔数组进行操作,使其仅返回公用列的列表?

How do I operate that NumPy boolean array on the Index object so it just gives back a list of the columns in common?

推荐答案

使用 :

a = np.intersect1d(df2.columns, df1.columns)
print (a)
['B' 'C']

a = df2.columns.intersection(df1.columns)
print (a)
Index(['B', 'C'], dtype='object')

后一种选择的替代语法:

Alternative syntax for the latter option:

df1.columns & df2.columns

这篇关于两个pandas数据框中共有的列的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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