gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:00:01 25 4
gpt4 key购买 nike

这是我的数据

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com