python - 如何在 python 中对列范围求和

标签 python pandas dataframe

这是我的数据

df 

No Name     Address    English  History  Math   Physics  Chemistry  Biology
1  Arthur   New York        80       65   100        89         92       94
2  Barthur  New Mexico      70       60    94        83         82       95

我做的是

df['科学'] = df['数学'] + df['物理'] + df['化学'] + df['生物学']

我的问题是,实际数据超过 900 列,如何替换 df['Math'] + df['Physics'] + df['Chemistry'] + df['Biology'] df['Math']df['Biology'] 求和(按范围)

我希望这个问题足够清楚

最佳答案

我想你需要iloc按职位选择:

df['sum'] = df.iloc[:, 3:].sum(axis=1)

或者删除不需要的数字列:

df['sum'] = df.drop('No', axis=1).sum(axis=1)

print (df)
   No     Name     Address  English  History  Math  Physics  Chemistry  \
0   1   Arthur    New York       80       65   100       89         92   
1   2  Barthur  New Mexico       70       60    94       83         82   

   Biology  sum  
0       94  520  
1       95  484  

编辑:

如果只需要从5到末尾的所有列:

print (df.iloc[:, 5:])
   Math  Physics  Chemistry  Biology
0   100       89         92       94
1    94       83         82       95

print (df.iloc[:, 3:5])
   English  History
0       80       65
1       70       60

df['A'] = df.iloc[:, 3:5].sum(axis=1)
df['Science'] = df.iloc[:, 5:].sum(axis=1)
print (df)
   No     Name     Address  English  History  Math  Physics  Chemistry  \
0   1   Arthur    New York       80       65   100       89         92   
1   2  Barthur  New Mexico       70       60    94       83         82   

   Biology    A  Science  
0       94  145      520  
1       95  130      484  

关于python - 如何在 python 中对列范围求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48923460/

相关文章:

python - 修改张量

python - 双 View SFM 的相机姿势不正确

python - 计算 DataFrame 中各组的差异和均值

python - pandas GroupBy 具有 NaN(缺失)值的列

python - pandas 变量的两步正则表达式

python - python 脚本完成后保持 Selenium 浏览器打开

python - 如何保存包含指针的 ctypes 对象

python - 正则表达式从多种格式的年龄范围 DataFrame 列中提取数字

python - 在 pandas 数据框中显示具有一个或多个 NaN 值的行

r - 如何计算data.frame中连续数字的数量?