car*_*mom 6 python python-3.x pandas
我正在考虑对数据帧进行合并操作,每个数据帧都有大量列.不希望结果具有两个具有相同名称的列.我试图查看两个框架之间共同的列名列表:
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])
Run Code Online (Sandbox Code Playgroud)
如何在Index对象上操作NumPy布尔数组,以便它只返回一个共同列的列表?
jez*_*ael 13
使用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')
Run Code Online (Sandbox Code Playgroud)
后一种选择的替代语法:
df1.columns & df2.columns
Run Code Online (Sandbox Code Playgroud)