我有一个包含两列的数据帧:一列包含一个0和一个值,另一列包含一个数值
ZeroOne Value
0 10
1 20
0 15
目标是生成一个新列,如果ZeroOne列包含“0”,则将value列的值放入其中。如果zerone值是1,那么新列应该是0。因此,在我的示例中,结果应该是:
ZeroOne Value Result
0 10 10
1 20 0
0 15 15
我试着做一个函数:
def function(a,b):
if a == 1:
return b
else:
return 0
然后把变量a和b
a = df['ZeroOne']
b = df['Value']
在这之后,我用这个函数添加了一个新的列
df['result'] = function(a,b)
它一直给我值错误:
The truth value of a Series is ambiguous. Use a.empty, a.bool(),
a.item(), a.any() or a.all().
我怎样才能达到我的目标?我做错了什么
对于这种情况,您可以使用numpy库中的
np.where
:它类似于亚当斯解,但你也可以给它添加其他条件,函数中的第一个空格给出了条件,如果它是真的会发生什么,如果它是错的会发生什么
尝试使用
where
:输出:
相关问题 更多 >
编程相关推荐