Pandas - 自动将缺失的列添加到数据框

sco*_*tin 1 dataframe pandas

我有一个列表,其中包含 pandas Dataframe 可以包含的所有可能的列。

possible_values = ['apples','banana','orange']
Run Code Online (Sandbox Code Playgroud)

我正在尝试执行检查,如果 Dataframe 不具有上述列表中的所有列,则需要将该列添加到 Dataframe 中,并将值设置为 0

例如,如果我的数据框包含以下列,则需要添加另外两列

df.columns = ['apples']
Run Code Online (Sandbox Code Playgroud)

预期产出

df.columns = ['apples','banana','orange']
Run Code Online (Sandbox Code Playgroud)

mao*_*aow 6

Something like this should work:

for fruit in set(possible_values).difference(df.columns):
    df.insert(len(df.columns), fruit, 0)
Run Code Online (Sandbox Code Playgroud)

set.difference gives you the columns not present in your Dataframe. The insert command then expects the position where to insert (in this case the end), the name and the default value (0)

EDIT: changed from df.columns.difference(possible_values) to set(possible_values).difference(df.columns)