lakshmen
lakshmen

Reputation: 29064

Sum only negative numbers across columns in dataframe Pandas

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?

Upvotes: 1

Views: 4228

Answers (5)

kelkka
kelkka

Reputation: 1004

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.

Upvotes: 0

gmds
gmds

Reputation: 19875

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

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

Upvotes: 4

Chris
Chris

Reputation: 29732

Another way is to use abs:

df['neg_sum'] = df.where(df != df.abs()).sum(1)

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71560

Use apply:

df['Sum']=df.apply(lambda x: x[x<0].sum(),axis=1)

Upvotes: 1

BENY
BENY

Reputation: 323226

Using mask

df.iloc[:,1:].where(df.iloc[:,1:]<0).sum(axis=1)

Upvotes: 3

Related Questions