两个 Pandas 数据框中的公共列列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48539195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
list of columns in common in two pandas dataframes
提问by cardamom
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 布尔数组,以便它只返回一个公共列的列表?
回答by jezrael
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