python pandas 新增列用if else 根据其他列条件进行赋值

python pandas 新增列用if else 根据其他列条件进行赋值

R语言转成python. 求助

R 语言如下

SingleMstepResult['ratio'] = ifelse(SingleMstepResult['P90']>SingleMstepResult['refUL'], 

SingleMstepResult['P90']/SingleMstepResult['refUL']-1,

1-SingleMstepResult['P10']/SingleMstepResult['refLL'])

Python 写成下面的不对

SingleMstepResult['ratio'] = (SingleMstepResult['P90']/SingleMstepResult['refUL']-1) if (SingleMstepResult['P90']>SingleMstepResult['refUL']) 

else (SingleMstepResult['P10']/SingleMstepResult['refLL'])


回答:

最简单的是借助 np.where(条件复杂的话用 np.select),其次是 df.apply,接着是 df.iterrows。比如:

python3">import numpy as np # 如果之前没有导入的话

SingleMstepResult['ratio'] = np.where(SingleMstepResult['P90'] > SingleMstepResult['refUL'], SingleMstepResult['P90'] / df['refUL'] - 1, 1 - SingleMstepResult['P10']/SingleMstepResult['refLL'])

以上是 python pandas 新增列用if else 根据其他列条件进行赋值 的全部内容, 来源链接: utcz.com/p/938164.html

回到顶部