2024-06-28 19:11:08 发布
网友
假设我有一个数据帧
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的assign方法,如果l可以包含一个值、一个数组或任何pandas系列构造函数,则这是一种稍微简洁的方法。
l
# 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
assign
您可以尝试直接赋值(假设您的数据帧名为df):
或者使用DataFrame的assign方法,如果
l
可以包含一个值、一个数组或任何pandas系列构造函数,则这是一种稍微简洁的方法。关于
assign
方法的Pandas文档:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html相关问题 更多 >
编程相关推荐