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

前端 未结 3 1072
遥遥无期
遥遥无期 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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-22 03:00

    you can use pd.cut() method in order to categorize your data:

    Demo:

    In [66]: events = pd.DataFrame(np.random.randint(0, 23, 10), columns=['hour'])
    
    In [67]: events
    Out[67]:
       hour
    0     5
    1    17
    2    12
    3     2
    4    20
    5    22
    6    20
    7    11
    8    14
    9     8
    
    In [71]: events['time_slice'] = pd.cut(events.hour, bins=[-1, 6, 12, 18, 23], labels=['night','morning','afternoon','evening'])
    
    In [72]: events
    Out[72]:
       hour time_slice
    0     5      night
    1    17  afternoon
    2    12    morning
    3     2      night
    4    20    evening
    5    22    evening
    6    20    evening
    7    11    morning
    8    14  afternoon
    9     8    morning
    
    0 讨论(0)
提交回复
热议问题