这是我的数据
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/