Skip to content Skip to sidebar Skip to footer

Select Column With Only One Negative Value

I'd like to select the columns that only have one negative value or none. How can I construct this looking at this example? I've been searching for something similar, didn't succee

Solution 1:

Use np.sign to get the signs. Look for negative signs. Get the count of negative numbers for each column. Compare against the threshold of 1 to get a mask. Select the column names from the mask.

Hence, the implementation -

df1.columns[(np.sign(df1)<0).sum(0)<=1].tolist()

Or directly compare against 0 to replace the use of np.sign -

df1.columns[(df1<0).sum(0)<=1].tolist()

This gives us the column names. To select entire columns, other solutions I think have covered it.

Solution 2:

You can use iloc to do that i.e

df1.iloc[:,((df1<0).sum(0) <=1).values]

or (Thanks Jon)

df1.loc[:,df1.lt(0).sum() <= 1]

Output:

          X         Z
0  0.292881  1.750350
1  1.291136  0.173370
2  0.616580  0.408267
3  0.269299  2.553580
4 -0.458071 -2.573784

Solution 3:

Or You can try :

df1.columns[(df1<0).sum(0).lt(1)]
Out[338]: Index(['X', 'Z'], dtype='object')

Post a Comment for "Select Column With Only One Negative Value"