将列表中具有零值的多列添加到 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
Add multiple columns with zero values from a list to a Pandas data frame
提问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 l
can 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 assign
method : 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