I have a dataframe in pandas looking like this:
A B
0 2 0
1 0 3
2 1 1
3 5 0
4 3 1
I need to create a new column based on condition in column A and column B:
if column A > 0 and column B > 0 : new column value = 1
else : new column value = 0
The new column should be like this:
A B new_column
0 2 0 0
1 0 3 0
2 1 1 1
3 5 0 0
4 3 1 1
I tried with np.where but return an error
df['new_column'] = np.where( (df['A']>0 & df['B']>0), 1 , 0)
This is the error:
TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
I tried apply but return error too:
def F(x):
if x['A'] > 0 & x['B'] > 0:
return 1
else:
return 0
df['new_column'] = df.apply(F, axis=1)
This is the error:
TypeError: ("unsupported operand type(s) for &: 'int' and 'float'", 'occurred at index 0')
I already converted column A and column B to numeric
df['A'] = pd.to_numeric(df['A'])
df['B'] = pd.to_numeric(df['B'])
I tried:
df['new_column'] = df[['A','B']].gt(0).all(1)
it returns True or False, not 0 / 1