将列表中的多个值为零的列添加到Pandas数据框架中

2024-06-28 19:11:08 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个数据帧

id col1 col2
1  1    foo
2  1    bar

以及列名列表

l = ['col3', 'col4', 'col5']

如何向数据框中添加值为零的新列?

id col1 col2 col3 col4 col5
1  1    foo     0    0    0
2  1    bar     0    0    0

Tags: 数据id列表foobarcol2col3col1
1条回答
网友
1楼 · 发布于 2024-06-28 19:11:08

您可以尝试直接赋值(假设您的数据帧名为df):

for col in l:
    df[col] = 0

或者使用DataFrame的assign方法,如果l可以包含一个值、一个数组或任何pandas系列构造函数,则这是一种稍微简洁的方法。

# create a dictionary of column names and the value you want
d = dict.fromkeys(l, 0)
df.assign(**d)

关于assign方法的Pandas文档:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html

相关问题 更多 >