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
  • 28,346
  • 66
  • 178
  • 276

5 Answers5

4

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

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

gmds
  • 19,325
  • 4
  • 32
  • 58
3

Using mask

df.iloc[:,1:].where(df.iloc[:,1:]<0).sum(axis=1)
BENY
  • 317,841
  • 20
  • 164
  • 234
2

Another way is to use abs:

df['neg_sum'] = df.where(df != df.abs()).sum(1)
Chris
  • 29,127
  • 3
  • 28
  • 51
1

Use apply:

df['Sum']=df.apply(lambda x: x[x<0].sum(),axis=1)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
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
  • 874
  • 7
  • 18