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

ⅰ亾dé卋堺 提交于 2021-02-07 19:30:18

问题


Goal here is to find the columns that does not exist in df and create them with null values.

I have a list of column names like below:

column_list = ('column_1', 'column_2', 'column_3')

When I try to check if the column exists, it gives out True for only columns that exist and do not get False for those that are missing.

for column in column_list:
    print df.columns.isin(column_list).any()

In PySpark, I can achieve this using the below:

for column in column_list:
        if not column in df.columns:
            df = df.withColumn(column, lit(''))

How can I achieve the same using Pandas?


回答1:


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



回答2:


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]})


来源:https://stackoverflow.com/questions/52934960/pandas-check-if-column-exists-in-df-from-a-list-of-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!