[英]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.