简体   繁体   中英

Create new Pandas columns based on conditional counts of all other columns

I have a Pandas data frame with around ~360 columns. I want to add another column to the other frame based on the count of whether in rest of the columns how many columns have a value greater than 0. Type of all my columns is float 64.

If this is my original dataframe

column A column B column C ...............Column Z 
0          1.5      6.77                   3.33
3.5        4.5      0                       0  
0           0       0.98                    0
.
.
.
2.35      4.32       0                      9.21 

I want to add a column to it like this which have count of all non zero columns for each row:

column A column B column C ...............Column Z  Column New
0          1.5      6.77                   3.33        3
3.5        4.5      0                       0          2
0           0       0.98                    0          1
.                                                      .
.                                                      .
.                                                      .
2.35      4.32       0                      9.21       3 

How can i add a column like this? I was trying this but getting all NaNs.

df['column_new']=df.apply(lambda x: (x > 0).count())

Not sure if this is the correct way approach this.

Just to give an idea this is how values in my original data frame are like. So i want a count of columns in the new column which don`t have zero value.

在此处输入图像描述

You're on the right track. The comparison to zero returns series of bools, so you can sum rather than count. You also don't need to apply this since you can compare the entire dataframe and then sum along the correct axis:

df = df.assign(count_gt_zero=(df > 0).sum(axis='columns'))

Another option with gt :

df['new_column'] = df.gt(0, axis=1).sum(axis=1)

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