简体   繁体   中英

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?

使用mask

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

使用apply

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

另一种方法是使用abs

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM