gpt4 book ai didi

python - Pandas 蟒 : how to create multiple columns from a list

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:22 25 4
gpt4 key购买 nike

我有一个包含要创建的列的列表:

new_cols = ['new_1', 'new_2', 'new_3']

我想在数据框中创建这些列并用零填充它们:

df[new_cols] = 0

获取错误:

"['new_1', 'new_2', 'new_3'] not in index"

这是真的,但很不幸,因为我想创建它们...

编辑:这是这个问题的副本:Add multiple empty columns to pandas DataFrame但是我也保留了这个,因为这里接受的答案是我正在寻找的简单解决方案,而不是他在那里接受的答案

编辑 2:虽然接受的答案是最简单的,但下面发布了有趣的单行解决方案

最佳答案

您需要逐一添加列。

for col in new_cols:
df[col] = 0

另请参阅 here 中的答案对于其他方法。

关于python - Pandas 蟒 : how to create multiple columns from a list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51495800/

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