Python_if_else_for循环函数应用

对标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 那一列的数据。写成两个【】不会改变原表数据,因为只是在展示过程中进行了修改。

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值