1

I have a df like this:

Index Parameters A B C D E 1 Apple 1 2 3 4 5 2 Banana 2 4 5 3 5 3 Potato 3 5 3 2 1 4 Tomato 1 1 1 1 1 5 Pear 4 5 5 4 3 

I want to add all the rows which has Parameter values as "Apple" , "Banana" and "Pear".

Output:

Index Parameters A B C D E 1 Apple 1 2 3 4 5 2 Banana 2 4 5 3 5 3 Potato 3 5 3 2 1 4 Tomato 1 1 1 1 1 5 Pear 4 5 5 4 3 6 Total 7 11 13 11 13 

My Effort:

  1. df[:,'Total'] = df.sum(axis=1) -- Works but I want specific values only and not all
  2. Tried by the index in my case 1,2 and 5 but in my original df the index can vary from time to time and hence rejected that solution.

Saw various answers on SO but none of them could solve my problem!!

1 Answer 1

2

First idea is create index by Parameters column and select rows for sum and last convert index to column:

L = ["Apple" , "Banana" , "Pear"] df = df.set_index('Parameters') df.loc['Total'] = df.loc[L].sum() df = df.reset_index() print (df) Parameters A B C D E 0 Apple 1 2 3 4 5 1 Banana 2 4 5 3 5 2 Potato 3 5 3 2 1 3 Tomato 1 1 1 1 1 4 Pear 4 5 5 4 3 5 Total 7 11 13 11 13 

Or add new row for filtered rows by membership with Series.isin and overwrite last added value by Total:

last = len(df) df.loc[last] = df[df['Parameters'].isin(L)].sum() df.loc[last, 'Parameters'] = 'Total' print (df) Parameters A B C D E Index 1 Apple 1 2 3 4 5 2 Banana 2 4 5 3 5 3 Potato 3 5 3 2 1 4 Tomato 1 1 1 1 1 5 Total 7 11 13 11 13 

Another similar solution is filtering all columns without first and add value in one element list:

df.loc[len(df)] = ['Total'] + df.iloc[df['Parameters'].isin(L).values, 1:].sum().tolist() 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.