user8403237
user8403237

Reputation:

Find the sum of columns even if the columns doesn't exist add zeros with it

I have following dataset:

coll1    col2    col3 
  2        3      4
  5        6      7
  8        9      1

I want to generate a another columns Let's say total, if I want to write the code:

df[total]=df['col1']+df['col2']+df['col3']+df['col4']+df['col5']

I know that col4 and col5 doesn't exists, I want write the code where even though col4 and col5 doesn't exits, It wont show any error, Rather I will add zero in the equation.

So the result of the first row will be 9. With out any error. How to code for it ?

Upvotes: 1

Views: 444

Answers (1)

cs95
cs95

Reputation: 402872

Use reindex, NaNs do not count towards the sum (in DataFrames):

col_list = ['col1', 'col2', 'col3', 'col4', 'col5']
df.reindex(col_list, axis=1).sum(axis=1)

This is only under the assumption that, for whatever reason, df.sum(axis=1) isn't applicable.

Upvotes: 2

Related Questions