python - 如果 Pandas 不可用,则添加列

标签 python pandas

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

如果数据框 (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 

有没有一种简单有效的方法呢。

最佳答案

您可以使用 pd.Index.uniondf.reindex

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)

关于python - 如果 Pandas 不可用,则添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66450668/

相关文章:

Python 使用 "quoted-printable"传输编码和 "utf-8"内容编码发送电子邮件

python - 远程机器人 : AttributeError: 'NoneType' object has no attribute 'format'

python - 使用 Numba 处理 pandas DataFrame 时间序列的有效方法

python - 使用 to_datetime 转换日期

python - 越界纳秒时间戳

python - 请求发布带有字典格式错误的数据

python - 在列表中的元素之间添加元素

python - 如何解析在查看源代码中不显示代码的网站?

python - 从 Pandas 的列中删除错误值

python - 使用 Python 按列分组并求和另一列的内容