Evaluating multiple conditions in if-then-else block in a Pandas DataFrame

前端 未结 3 1074
遥遥无期
遥遥无期 2021-01-22 02:17

I want to create a new column in a Pandas DataFrame by evaluating multiple conditions in an if-then-else block.

if events.hour <= 6:
    events[\'time_slice\         


        
3条回答
  •  悲哀的现实
    2021-01-22 02:57

    Here's a NumPy approach to it -

    tags = ['night','morning','afternoon','evening']
    events['time_slice'] = np.take(tags,((events.hour.values-1)//6).clip(min=0))
    

    Sample run -

    In [130]: events
    Out[130]: 
       hour time_slice
    0     0      night
    1     8    morning
    2    16  afternoon
    3    20    evening
    4     2      night
    5    14  afternoon
    6     7    morning
    7    18  afternoon
    8     8    morning
    9    22    evening
    

提交回复
热议问题