The Python Oracle

Pandas: Check if column exists in df from a list of columns

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Realization

--

Chapters
00:00 Pandas: Check If Column Exists In Df From A List Of Columns
00:37 Accepted Answer Score 11
00:48 Answer 2 Score 9
00:59 Thank you

--

Full question
https://stackoverflow.com/questions/5293...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas

#avk47



ACCEPTED ANSWER

Score 11


Here is how I would approach:

import numpy as np

for col in column_list:
    if col not in df.columns:
        df[col] = np.nan



ANSWER 2

Score 9


Using np.isin, assign and unpacking kwargs

s = np.isin(column_list, df.columns)
df = df.assign(**{k:None for k in np.array(column_list)[~s]})