如何在python中对列范围求和
这是我的数据如何在python中对列范围求和,python,pandas,dataframe,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
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['Science']=df['Math']+df['Physics']+df['Chemistry']+df['Biology']
我的问题是,实际数据超过900列,如何替换df['Math']+df['Physics']+df['Chemistry']+df['Biology']
从df['Math']
到df['Biology']
(按范围计算)
我希望这个问题足够清楚我认为您需要按职位选择:
df['sum'] = df.iloc[:, 3:].sum(axis=1)
或删除不需要的数字列:
df['sum'] = df.drop('No', axis=1).sum(axis=1)
编辑: 如果只需要从
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
我也不需要英语和历史,我需要的是
df['Science']=df['Math']+df['Physics']+df['Chemistry']+df['Biology']
。请编辑你的答案。是否可以按组定义所有主题?您应该df['Science']=df.iloc[:,5:9].sum(axis=1)
,但您可以回答这个问题completely@NabihBawazir-是的,你是对的。感谢您的接受,祝您愉快!
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