KeyError: None of [Index([(….)])] are in the columns for a list of columns generated with df.columns

Question:

I have a df_a that contains all columns. Then I have df_b that contains a subset of this dataframe. I want to select the columns that are in df_b from df_a.

Why does the following code not work?

df_a[[df_b.columns]]  

It throws a KeyError "None of [Index([(....), (....))], dtype='object)] are in the [columns]. Why?

Asked By: RogerKint

||

Answers:

Inner [] is redundant, you can try

df_a[df_b.columns]
# or
df_a.reindex(columns=df_b.columns)
Answered By: Ynjxsjmh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.