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

嗯heng
  • 21

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'])
回复
阅读 333
1 个回答
✓ 已被采纳

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

import numpy as np # 如果之前没有导入的话
SingleMstepResult['ratio'] = np.where(SingleMstepResult['P90'] > SingleMstepResult['refUL'], SingleMstepResult['P90'] / df['refUL'] - 1, 1 - SingleMstepResult['P10']/SingleMstepResult['refLL'])
宣传栏