Pandas: how to sum dynamically varying columns

I want to add a new column where each row is the sum of the row values in the chosen columns. Please note that the number of columns are not fixed. It varies dynamically. Say I have this dataframe and a list where I specify the columns to be added: (The actual number of columns are much higher)

df
           col1  col2  col3  col4
        0    56    22   320   300
        1    34    25   220   220
        2    45    27   120   120
        3    78    35   830    83


   add = ['col1', 'col4']

The add list varies. I then want a new column where each row is the sum of the row values in the chosen columns, specified in add. Something like this:

for col in add:
    df['sum'] += df[col]

And the desired result:

   col1  col2  col3  col4  sum
0    56    22   320   300  356
1    34    25   220   220  254
2    45    27   120   120  165
3    78    35   830    83  161

but the above code is not working. Any hints?

Upvotes: 0

Views: 870

Answers (2)

Codewizard_26
Codewizard_26

Reputation: 68

We can try it without using 'for' loop by simply using df['col1','col2'].sum() and then merging the 'sum' column with the existing dataframe .

Upvotes: 0

Kenan
Kenan

Reputation: 14094

Sum along the columns

add = ['col1', 'col4']
df['Sum'] = df[add].sum(axis=1)
   col1  col2  col3  col4  sum
0    56    22   320   300  356
1    34    25   220   220  254
2    45    27   120   120  165
3    78    35   830    83  161

Upvotes: 1

Related Questions