首页 > 解决方案 > 如何在没有循环的情况下为多列设置值

问题描述

如何在没有循环的情况下为几列设置值?

df.loc[:, ['test2', 'test3']] = 0

或者

df[['test2', 'test3']] = 0

我希望它在'test2'和'test3'列中设置值0,但它返回错误,即df中没有这样的列。

标签: pythonpandas

解决方案


如果您尝试创建新列,您可以使用df.assign()

df.assign(test1=0,test2=0)

这将创建 2 列,其值为0


推荐阅读