dropping columns based on another dataframe & adding a panda series

Viewed 25

Let s assume we have 3 dataframes.

  • df1 has 14 columns
  • df2 has 26 columns (which was created from a merge of df1 with another dataframe)
  • df3 that has 15 columns

What I want is to drop the columns of df2. I want to keep the common columns that they have with df1 and then append 1 extra column from df3(that I will specify by name) I tried something like the following

df2 = df2[(df1.column) & df3['Name'])

but it did not work I also tried

df2 = pd.concat([df1, df3['Name'])

but again it did not work (it returned an empty dataframe)

1 Answers

Use an index intersection:

new_df2 = df2[list(df2.columns.intersection(df1.columns))+['Name']]
Related