简体   繁体   中英

Perform logical operations on every column of a pandas dataframe?

I'm trying to create a new df column based on a condition to be validated in the all the rest of the columns per each row.

df = pd.DataFrame([[1, 5, 2, 8, 2], [2, 4, 4, 20, 5], [3, 3, 1, 20, 2], [4, 2, 2, 1, 0], 
                  [5, 1, 4, -5, -4]],
                  columns=['a', 'b', 'c', 'd', 'e'],
                  index=[1, 2, 3, 4, 5])

I tried:

df['f'] = ""
df.loc[(df.any() >= 10), 'f'] = df['e'] + 10

However I get:

IndexingError: Unalignable boolean Series key provided

This is the desired output:

    a   b   c   d   e   f
1   1   5   2   8   2   
2   2   4   4   20  5   15
3   3   3   1   20  2   12
4   4   2   2   1   0
5   5   1   4  -5  -4

Use

In [984]: df.loc[(df >= 10).any(1), 'f'] = df['e']  + 10

In [985]: df
Out[985]:
   a  b  c   d  e     f
1  1  5  2   8  2   NaN
2  2  4  4  20  5  15.0
3  3  3  1  20  2  12.0
4  4  2  2   1  0   NaN
5  5  1  4  -5 -4   NaN

Note that:

df.any()
a    True
b    True
c    True
d    True
e    True
f    True
dtype: bool

df.any() >= 10
a    False
b    False
c    False
d    False
e    False
f    False
dtype: bool

I assume you want to check if any value in a column is >= 10 . That would be done with (df >= 10).any(axis=1) .


You should be able to do this in one step, using np.where :

df['f'] = np.where((df >= 10).any(axis=1), df.e + 10, '')    
df
   a  b  c   d  e   f
1  1  5  2   8  2    
2  2  4  4  20  5  15
3  3  3  1  20  2  12
4  4  2  2   1  0    
5  5  1  4  -5 -4   

If you'd prefer NaN s instead of blanks, use:

df['f'] = np.where((df >= 10).any(axis=1), df.e + 10, np.nan)   
df
   a  b  c   d  e     f
1  1  5  2   8  2   NaN
2  2  4  4  20  5  15.0
3  3  3  1  20  2  12.0
4  4  2  2   1  0   NaN
5  5  1  4  -5 -4   NaN

By using max

df['f'] = ""
df.loc[df.max(1)>=10,'f']=df.e+10


Out[330]: 
   a  b  c   d  e   f
1  1  5  2   8  2    
2  2  4  4  20  5  15
3  3  3  1  20  2  12
4  4  2  2   1  0    
5  5  1  4  -5 -4    

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