1

I would like to sum by only negative numbers across all the columns in a dataframe.

I have seen this post: Pandas: sum up multiple columns into one column

My data looks like this:

But I would like to sum only the negative numbers. How do i do that?

lakshmen
  • 27,102
  • 64
  • 169
  • 262

5 Answers5

4

I would suggest you avoid apply; it can be slow.

This will work: df[df < 0].sum()

gmds
  • 17,927
  • 4
  • 26
  • 51
3

Using mask

df.iloc[:,1:].where(df.iloc[:,1:]<0).sum(axis=1)
BENY
  • 296,997
  • 19
  • 147
  • 204
2

Another way is to use abs:

df['neg_sum'] = df.where(df != df.abs()).sum(1)
Chris
  • 27,139
  • 3
  • 23
  • 44
1

Use apply:

df['Sum']=df.apply(lambda x: x[x<0].sum(),axis=1)
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
0

Here's my solution, modified from my answer in the quoted question:

df = pd.DataFrame({'a': [-1,2,3], 'b': [-2,3,4], 'c':[-3,4,5]})

column_names = list(df.columns)
df['neg_sum']= df[df[column_names]<0].sum(axis=1)

This answer allows for selecting the exact columns by name instead of taking all columns.

kelkka
  • 636
  • 6
  • 17