gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:22:03 25 4
gpt4 key购买 nike

我使用类似于以下代码的一长串代码来检查并创建一个值为“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com