我有一个如下所示的数据框:
df =
result
0 -43.859440
1 -20.000000
2 63.666667
3 116.500000
4 -22.333333
5 12.500000
6 -103.705882
7 322.800000
8 -513.888889
9 774.000000
10 -4508.000000
如果对应行count
中的值> 0,我想产生另一列称为result
的元素1,如果小于零则为-1。
我当前的代码:
df['count'] = [1 if df['result']>0 else -1 if df['result']>-1]
我现在的输出:
SyntaxError: invalid syntax
我的预期输出:
df =
result count
0 -43.859440 -1
1 -20.000000 -1
2 63.666667 1
3 116.500000 1
.
.
我当前的代码有什么问题?
答案 0 :(得分:1)
您可以使用np.where()
。见下文:
import numpy as np
df['count'] = np.where(df['result']>0,1,0)