Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use numpy.intersect1d or 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...