我在熊猫中有一个数据框,如下所示:
A B
0 2 0
1 0 3
2 1 1
3 5 0
4 3 1
我需要根据A列和B列的条件创建一个新列:
if column A > 0 and column B > 0 : new column value = 1
else : new column value = 0
新列应如下所示:
A B new_column
0 2 0 0
1 0 3 0
2 1 1 1
3 5 0 0
4 3 1 1
我尝试过 np.where ,但返回错误
df['new_column'] = np.where( (df['A']>0 & df['B']>0), 1 , 0)
这是错误:
TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
我尝试应用,但也返回错误:
def F(x):
if x['A'] > 0 & x['B'] > 0:
return 1
else:
return 0
df['new_column'] = df.apply(F, axis=1)
这是错误:
TypeError: ("unsupported operand type(s) for &: 'int' and 'float'", 'occurred at index 0')
我已经将A列和B列转换为数字
df['A'] = pd.to_numeric(df['A'])
df['B'] = pd.to_numeric(df['B'])
我尝试过:
df['new_column'] = df[['A','B']].gt(0).all(1)
它返回True或False,而不是0/1