Reputation: 29064
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
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
Reputation: 19875
I would suggest you avoid apply
; it can be slow.
This will work: df[df < 0].sum()
Upvotes: 4
Reputation: 29732
Another way is to use abs
:
df['neg_sum'] = df.where(df != df.abs()).sum(1)
Upvotes: 2