phoenix4
phoenix4

Reputation: 59

How to select columns from the dataframe based on variables from another dataframe

I wanted to select only those columns from df2 which are equal to the variables of df1 in python pandas

df1

parameter (column name)

a
b
c

df2

w  x  a  c  z
3  1  5  6  1
5  67 4  3  56
8  12 6  1  23

my expected output is

a c
5 6
4 3
6 1

Upvotes: 2

Views: 925

Answers (1)

jezrael
jezrael

Reputation: 862521

Use intersection or isin for boolean mask:

df3 = df2[df.columns.intersection(df1['parameter'])]

Or:

df3 = df2.loc[:, df.columns.isin(df1['parameter'])]

Upvotes: 1

Related Questions