Python 将列表中的多个零值列添加到数据框中
假设我有一个数据帧Python 将列表中的多个零值列添加到数据框中,python,pandas,Python,Pandas,假设我有一个数据帧 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): 或者使用DataFrame的assign方法,如果l可以包含一个值、一个数组或任何
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): 或者使用DataFrame的assign方法,如果
l
可以包含一个值、一个数组或任何构造函数,那么这是一种稍微干净的方法
# create a dictionary of column names and the value you want
d = dict.fromkeys(l, 0)
df.assign(**d)
有关
assign
方法的文档:您的d
可以更简单地写成dict.fromkeys(l,0)
。(不过,警告:由于我们使用的是字典,因此不能保证顺序是l
)谢谢!添加了更改。如何强制列的数据类型为int32而不是float64?我尝试了df[col]=int(0)
,还用astype(int)
转换了整个列,但它不起作用。奇怪的是,它应该足够做df[col]=df[col]。astype({col:“int32”})
这将有助于发布一个可复制的示例。使用字典分配来解释的示例
# create a dictionary of column names and the value you want
d = dict.fromkeys(l, 0)
df.assign(**d)