Python 列添加(如果不可用)

Python 列添加(如果不可用),python,pandas,Python,Pandas,我使用类似于下面代码的长代码列表来检查并创建一个值为“0”的列 如果数据帧(df)中不存在列 有没有一种简单有效的方法可以做到这一点。您可以使用: 你可以用 安装程序 创建不在df 结合新构造的数据帧 if 'E184' not in df: df['E184'] = 0 if 'E185' not in df: df['E185'] = 0 if 'E187' not in df: df['E187'] = 0 if 'E186' not in df: df['E186'] = 0

我使用类似于下面代码的长代码列表来检查并创建一个值为“0”的列

如果数据帧(df)中不存在列

有没有一种简单有效的方法可以做到这一点。

您可以使用:

你可以用

安装程序
创建不在
df

结合新构造的数据帧
if 'E184' not in df: df['E184'] = 0
if 'E185' not in df: df['E185'] = 0 
if 'E187' not in df: df['E187'] = 0 
if 'E186' not in df: df['E186'] = 0 
if 'E176' not in df: df['E176'] = 0 
if 'E177' not in df: df['E177'] = 0 
if 'E181' not in df: df['E181'] = 0 
if 'E210' not in df: df['E210'] = 0 
if 'E175' not in df: df['E175'] = 0 
if 'E209' not in df: df['E209'] = 0 
if 'E174' not in df: df['E174'] = 0 
if 'E212' not in df: df['E212'] = 0 
if 'E211' not in df: df['E211'] = 0 
if 'E154' not in df: df['E154'] = 0 
if 'E219' not in df: df['E219'] = 0 
if 'E230' not in df: df['E230'] = 0 
if 'E220' not in df: df['E220'] = 0 
if 'E157' not in df: df['E157'] = 0 
if 'E188' not in df: df['E188'] = 0 
if 'E234' not in df: df['E234'] = 0 
codes = ['E184', 'E185', 'E187', 'E186', 'E176', 'E177', 'E181', 'E210', 'E175',
         'E209', 'E174', 'E212', 'E211', 'E154', 'E219', 'E230', 'E220', 'E157',
         'E188','E234']

df = df.reindex(columns = set(df.columns.to_list() + codes), fill_value = 0)
codes = ['E184', 'E185', 'E187', 'E186', 'E176', 'E177', 'E181', 'E210', 'E175',
         'E209', 'E174', 'E212', 'E211', 'E154', 'E219', 'E230', 'E220', 'E157',
         'E188','E234']

df.reindex(df.columns.union(codes, sort=False), fill_value=0, axis=1)
df = pd.DataFrame({'E001': [1, 2, 3]})

df

   E001
0     1
1     2
2     3
codes = ['E001', 'E002', 'E003', 'E004']

df.assign(**dict.fromkeys({*codes} - {*df}, 0))

   E001  E002  E004  E003
0     1     0     0     0
1     2     0     0     0
2     3     0     0     0
codes = ['E001', 'E002', 'E003', 'E004']

df.combine_first(pd.DataFrame(0, df.index, codes))

   E001  E002  E004  E003
0     1     0     0     0
1     2     0     0     0
2     3     0     0     0