如何在python中求和列范围

2024-09-30 20:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的数据

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']到{}(按范围)

我希望这个问题足够清楚


Tags: 数据nonamedfnewenglishaddressmath
1条回答
网友
1楼 · 发布于 2024-09-30 20:28:57

我想您需要^{}按职位选择:

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

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

^{pr2}$
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  

相关问题 更多 >