Pandas: Check if column exists in df from a list of columns
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Over Ancient Waters Looping
--
Chapters
00:00 Question
00:52 Accepted answer (Score 9)
01:06 Answer 2 (Score 6)
01:23 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
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Over Ancient Waters Looping
--
Chapters
00:00 Question
00:52 Accepted answer (Score 9)
01:06 Answer 2 (Score 6)
01:23 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]})