对标Mysql中case when 函数,在Pyhon中可使用for+if函数。
代码如下:
for i in range(len(tot_2019_lo.index)):
print(i)
if (tot_2019_lo.iloc[i]['a11']>=7) & (tot_2019_lo.iloc[i]['d1']>=48):
tot_2019_lo.loc[tot_2019_lo.index==i,'rule_seg'] ='rule_a'
elif (tot_2019_lo.iloc[i]['a11']>=7) & (tot_2019_lo.iloc[i]['a1']>=7) & (tot_2019_lo.iloc[i]['a6']>=86):
tot_2019_lo.loc[tot_2019_lo.index==i,'rule_seg'] ='rule_b'
elif (tot_2019_lo.iloc[i]['f1']<=485) & (tot_2019_lo.iloc[i]['e1']<=56) & (tot_2019_lo.iloc[i]['g1']<=417):
tot_2019_lo.loc[tot_2019_lo.index==i,'rule_seg'] ='rule_c'
elif (tot_2019_lo.iloc[i]['c7']=='Ct') | (tot_2019_lo.iloc[i]['c16']=='Ct'):
tot_2019_lo.loc[tot_2019_lo.index==i,'rule_seg'] ='rule_d'
elif (tot_2019_lo.iloc[i]['c3']=='A' ) | (tot_2019_lo.iloc[i]['c3']=='B') | (tot_2019_lo.iloc[i]['c3']=='C'):
tot_2019_lo.loc[tot_2019_lo.index==i,'rule_seg'] ='rule_e'
else:
tot_2019_lo.loc[tot_2019_lo.index==i,'rule_seg'] ='rule_null'
坑1:如果写成tot_2019_lo.iloc[tot_2019_lo.index=i,‘all’]会报错。原因:其会定位到tot_2019_lo这张表的某一列,并不是单纯的判断语句
坑2:必须用&,且每个条件用括号括起来
坑3:写成如下可更改tot_2019_lo 那一列的数据。写成两个【】不会改变原表数据,因为只是在展示过程中进行了修改。