首页 > 解决方案 > 如何为熊猫数据框的特定列添加值?

问题描述

我必须对 pandas DataFrame 的特定列执行相同的算术运算。我这样做

c.loc[:,'col3'] += cons
c.loc[:,'col5'] += cons
c.loc[:,'col6'] += cons

应该有一种更简单的方法可以在一次操作中完成所有这些操作。我的意思是col3,col5,col6在一个命令中更新。

标签: pythonpandasdataframe

解决方案


pd.DataFrame.loc标签索引接受列表:

df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])

df.loc[:, ['B', 'C']] += 10

print(df)

   A   B   C
0  1  12  13
1  4  15  16

推荐阅读