multiple if else conditions in pandas dataframe and derive multiple columns

前端 未结 3 732
有刺的猬
有刺的猬 2020-12-05 21:30

I have a dataframe like below.

import pandas as pd
import numpy as np
raw_data = {\'student\':[\'A\',\'B\',\'C\',\'D\',\'E\'],
        \'score\': [100, 96, 8         


        
3条回答
  •  盖世英雄少女心
    2020-12-05 22:03

    you can use also apply with a custom function on axis 1 like this :

    def color_selector(x):
        if (x['trigger1'] <= x['score'] < x['trigger2']) and (x['height'] < 8):
            return 'Red'
        elif (x['trigger2'] <= x['score'] < x['trigger3']) and (x['height'] < 8):
            return 'Yellow'
        elif (x['trigger3'] <= x['score']) and (x['height'] < 8):
            return 'Orange'
        elif (x['height'] > 8):
            return ''
    df2 = df2.assign(flag=df2.apply(color_selector, axis=1))
    

    you will get something like this :

提交回复
热议问题