将列表中具有零值的多列添加到Pandas数据框 [英] Add multiple columns with zero values from a list to a Pandas data frame
本文介绍了将列表中具有零值的多列添加到Pandas数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个数据框
id col1 col2
1 1 foo
2 1 bar
以及列名列表
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
推荐答案
您可以尝试直接分配(假设您的数据框名为df):
You could try direct assignment (assuming your dataframe is named df):
for col in l:
df[col] = 0
或者使用DataFrame的assign方法,如果l
可以包含一个值,一个数组或任何pandas Series构造函数,则这是一种比较干净的方法.
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.
# create a dictionary of column names and the value you want
d = dict.fromkeys(l, 0)
df.assign(**d)
assign
方法上的熊猫文档: http ://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html
Pandas Documentation on the assign
method : http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html
这篇关于将列表中具有零值的多列添加到Pandas数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文