Using conditional to generate new column in pandas dataframe

前端 未结 5 1901
-上瘾入骨i
-上瘾入骨i 2020-11-29 02:26

I have a pandas dataframe that looks like this:

   portion  used
0        1   1.0
1        2   0.3
2        3   0.0
3        4   0.8

I\'d

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 02:48

    You can define a function which returns your different states "Full", "Partial", "Empty", etc and then use df.apply to apply the function to each row. Note that you have to pass the keyword argument axis=1 to ensure that it applies the function to rows.

    import pandas as pd
    
    def alert(c):
      if c['used'] == 1.0:
        return 'Full'
      elif c['used'] == 0.0:
        return 'Empty'
      elif 0.0 < c['used'] < 1.0:
        return 'Partial'
      else:
        return 'Undefined'
    
    df = pd.DataFrame(data={'portion':[1, 2, 3, 4], 'used':[1.0, 0.3, 0.0, 0.8]})
    
    df['alert'] = df.apply(alert, axis=1)
    
    #    portion  used    alert
    # 0        1   1.0     Full
    # 1        2   0.3  Partial
    # 2        3   0.0    Empty
    # 3        4   0.8  Partial
    

提交回复
热议问题