简体   繁体   English

两个pandas数据帧中共有的列列表

[英]list of columns in common in two pandas dataframes

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])

How do I operate that NumPy boolean array on the Index object so it just gives back a list of the columns in common? 如何在Index对象上操作NumPy布尔数组,以便它只返回一个共同列的列表?

Use numpy.intersect1d or intersection : 使用numpy.intersect1d或者intersection

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

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

相关问题 Pandas:在公共列上添加两个数据帧 - Pandas: Adding two dataframes on the common columns 比较两个 Python Pandas 数据框的 2 列并获取公共行 - Comparing 2 columns of two Python Pandas dataframes and getting the common rows Pandas 给定公共列的两个不同大小的数据框之间的算术 - Pandas arthmetic between two different sized dataframes given common columns 将 pandas 中的两个数据框与公共信息合并为列或单元格 - Merge two dataframes in pandas with common info as columns or as cells 加入/合并两个或多个 pandas 数据框,它们共有 4 列 - Join/Merge two or more pandas dataframes which have 4 columns in common 如何使用列表理解来查找所有 Pandas 数据帧共有的列 - How to use list comphrehension to find columns common to all Pandas dataframes Map 两个具有公共列的数据框 - Map two dataframes with Common columns 比较两个数据帧中公共行的pandas数据帧 - Compare pandas dataframes for common rows in two dataframes python / pandas - 查找两个数据框之间的公共列,并创建另一个具有相同列的数据框以显示它们的差异 - python / pandas - Find common columns between two dataframes, and create another one with same columns showing their difference 比较两个Pandas数据框在公共日期的差异 - Comparing two Pandas dataframes for differences on common dates
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM