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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34667973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:28:28  来源:igfitidea点击:

Add multiple columns with zero values from a list to a Pandas data frame

pythonpandas

提问by arkisle

Say I have a data frame

说我有一个数据框

id col1 col2
1  1    foo
2  1    bar

And a list of column names

以及列名列表

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

How do I add new columns to the data frame with zero as values?

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

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

回答by Thtu

You could try direct assignment (assuming your dataframe is named df):

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

for col in l:
    df[col] = 0

Or use the DataFrame's assign method, which is a slightly cleaner way of doing it if lcan contain a value, an array or any pandas Series constructor.

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

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

Pandas Documentation on the assignmethod : http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html

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