Pandas - 如果不存在则创建新列

Kev*_*ash 1 dataframe pandas

我有一个以下格式的数据框

col_1, col_2, col_3
1, 2, 3
2, 3, 4
2, 3, 5
Run Code Online (Sandbox Code Playgroud)

我正在尝试检查数据框是否有一组列,如果没有,我想将它们创建为数据框中的新列

cols_to_check = ['col_1', 'col_2', 'col_6', 'col_9']
Run Code Online (Sandbox Code Playgroud)

为此,我想继续创建col_6col_9因为它们不存在于数据框中。

最终输出:

col_1, col_2, col_3, col_6, col_9
1, 2, 3, 0, 0
2, 3, 4, 0, 0
2, 3, 5, 0, 0
Run Code Online (Sandbox Code Playgroud)

wwn*_*nde 5

使用重新索引

cols_to_check = ['col_1','col_2', 'col_3', 'col_6', 'col_9']
df.reindex(columns=cols_to_check).fillna(0)
Run Code Online (Sandbox Code Playgroud)

以防万一,您不确定所有 df 列是否都包含在新列表中,请利用集合进行检查并使用集合并添加

cols_to_check = ['col_1','col_2', 'col_3', 'col_6', 'col_9']
new_list =list(set(df.columns).union(cols_to_check))
new_df=df.reindex(columns=sorted(new_list)).fillna(0)
print(new_df)



   col_1  col_2  col_3  col_6  col_9
0      1      2      3    0.0    0.0
1      2      3      4    0.0    0.0
2      2      3      5    0.0    0.0
Run Code Online (Sandbox Code Playgroud)