gpt4 book ai didi

python - 将列表中具有零值的多个列添加到 Pandas 数据框中

转载 作者:行者123 更新时间:2023-12-02 06:10:22 24 4
gpt4 key购买 nike

假设我有一个数据框

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

最佳答案

您可以尝试直接分配(假设您的数据框名为 df):

for col in l:
df[col] = 0

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

# 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

关于python - 将列表中具有零值的多个列添加到 Pandas 数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34667973/

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