Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sum a column range in python

Here's my data

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

What I did is

df['Science'] = df['Math'] + df['Physics'] + df['Chemistry'] + df['Biology']

My problem is, the actual data is more than 900 column, how do I replace df['Math'] + df['Physics'] + df['Chemistry'] + df['Biology'] to sum from df['Math'] to df['Biology'] (by range)

I hope this question is clear enough

like image 476
Nabih Bawazir Avatar asked Jan 28 '23 15:01

Nabih Bawazir


1 Answers

I think you need iloc for select by positions:

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

Or remove numeric columns which dont need:

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  

EDIT:

If need only all columns from 5 to the end:

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  
like image 188
jezrael Avatar answered Jan 31 '23 03:01

jezrael