multiple if else conditions in pandas dataframe and derive multiple columns

前端 未结 3 731
有刺的猬
有刺的猬 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:04

    Here is a way to use numpy.select() for doing this in a non cluttered way:

    conditions = [
        (df2['trigger1'] <= df2['score']) & (df2['score'] < df2['trigger2']) & (df2['height'] < 8),
        (df2['trigger2'] <= df2['score']) & (df2['score'] < df2['trigger3']) & (df2['height'] < 8),
        (df2['trigger3'] <= df2['score']) & (df2['height'] < 8),
        (df2['height'] > 8)
    ]
    
    choices = ['Red','Yellow','Orange', np.nan]
    df['Flag1'] = np.select(conditions, choices, default=np.nan)
    

提交回复
热议问题