Skip to main content
 首页 » 编程设计

python之为 Pandas 中列的子集添加值

2025年05月04日14sky-heaven

对于以下数据框:

index    A    B       C    
0        3    word    7 
1        4    type    3 
2        8    manic   4 
3        9    tour    6 

我要为 A 列的子集添加值。这是我的代码:

df.A=  df.loc[0:2, 'A' ] + 30 

但这是结果:

  index       A      B       C    
    0        33    word    7 
    1        34    type    3 
    2        38    manic   4 
    3              tour    6 

使 A 列第四行的值为“空”。有什么建议吗?

请您参考如下方法:

你可以使用+=:

df.loc[0:2,'A']+=30 
 
df 
Out[11]:  
   index   A      B  C 
0      0  33   word  7 
1      1  34   type  3 
2      2  38  manic  4 
3      3   9   tour  6