python np.Where with two conditions

Asked

Viewed 301 times

3

Hello,

I have the following dataframe:

import pandas as pd
import numpy as np

x = pd.DataFrame({'A': [1,2,3,0],
                  'B': [5,0,0,1]})

What I want is to create a column’D', which is True if the two columns 'A' and 'B' are > 0

What I’ve already tried:

x['D'] = x.A > 0 or x.B > 0

Valueerror: The Truth value of a Series is ambiguous. Use a.Empty, a.bool(), a.item(), a.any() or a.all().

I also tried to:

x['D'] = np.where((x.A >0) or (x.B > 0), True, False)

Does anyone know how I can do it?

2 answers

3


I got.

x['D'] = np.where((x.A > 0) | (x.B > 0), True, False)

0

You could also have used the command .any(1), that would check on each Dataframe line if any of the values is True, this way:

x['D'] = (x[['A','B']] > 0).any(1)

    A   B   D
0   1   5   True
1   2   0   True
2   3   0   True
3   0   1   True

If your Dataframe was composed only of columns A and B, nor would it be necessary to select them.

x['D'] = (x > 0).any(1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.