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

前端 未结 3 1109
遥遥无期
遥遥无期 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:49

    You could create a function:

    def time_slice(hour):
        if hour <= 6:
            return 'night'
        elif hour <= 12:
            return 'morning'
        elif hour <= 18:
            return 'afternoon'
        elif hour <= 23:
            return 'evening'
    

    then events['time_slice'] = events.hour.apply(time_slice) should do the trick.

提交回复
热议问题