我有以下数据框:
example = pd.DataFrame({"dirr":[1,0,-1,-1,1,-1,0],
"value": [125,130,80,8,150,251,18],
"result":[np.NaN for _ in range(7)]})
Run Code Online (Sandbox Code Playgroud)
我想用 cummin() 和 cummax() 执行以下操作:
example["result"].apply(lambda x : x= example["value"].cummax() if example["dirr"]==1
else x= example["value"].cummin() if example["dirr"]==-1
else x= NaN if if example["dirr"]==0
)
Run Code Online (Sandbox Code Playgroud)
这是返回:error: invalid syntax。
谁能帮我纠正一下吗?
这将是预期的输出:
example = pd.DataFrame({"dirr":[1,0,-1,-1,1,-1,0],
"value": [125,130,80,8,150,251,18],
"result":[125, NaN, 80, 8, 150, 8, NaN]})
Run Code Online (Sandbox Code Playgroud)
编辑:
因此,根据 @su79eu7k 的答案,以下函数将执行以下操作:
def calc(x):
if x['dirr'] == 1:
return np.diag(example["value"].cummax())
elif x['dirr'] == -1:
return np.diag(example["value"].cummin())
else:
return np.nan
Run Code Online (Sandbox Code Playgroud)
我应该能够将其推入 lambda,但仍然被语法错误阻止......我仍然没有看到?
example["result"]=example.apply(lambda x : np.diag(x["value"].cummax()) if x["dirr"]==1
else np.diag(x["value"].cummin()) if x["dirr"]==-1
else NaN if x["dirr"]==0
)
Run Code Online (Sandbox Code Playgroud)
如果你们最后一点小小的推动,我们将不胜感激。
我认为@3novak 的解决方案既简单又快速。但如果你真的想使用apply函数,
def calc(x):
if x['dirr'] == 1:
return example["value"].cummax()
elif x['dirr'] == -1:
return example["value"].cummin()
else:
return np.nan
example['result'] = np.diag(example.apply(calc, axis=1))
print example
dirr result value
0 1 125.0 125
1 0 NaN 130
2 -1 80.0 80
3 -1 8.0 8
4 1 150.0 150
5 -1 8.0 251
6 0 NaN 18
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5471 次 |
| 最近记录: |