我有以下数据帧:

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)]})

我想用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
                              )

这将返回: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]})

编辑:
因此,根据@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

我应该可以把它塞进一个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
                              )

最后一个小小的推动你们会非常感激的。

最佳答案

我认为@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

关于python - Pandas -Python:Apply()和if/then逻辑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41420929/

10-12 22:26
查看更多