converting the duration column into short, medium, long values

Viewed 35

how to Convert the duration column into short, medium, long values. Come up with the boundaries by splitting the duration range in 3 equal size ranges

df['duration'].head()                                                                             

Output:

0      01:13
1      01:09
2      01:40
3      00:48
4      00:49
       ...  
98     00:52
99     01:10
100    01:05
101    01:09
102    00:58
Name: duration, Length: 103, dtype: object
1 Answers

You can use pandas.cut on the Series of Timedelta after conversion with pandas.to_timedelta:

df['bin'] = pd.cut(pd.to_timedelta(df['duration']+':00'),
                   bins=3, labels=['low', 'medium', 'high'])

NB. assuming a HH:MM format here, for MM:SS, use '00:'+df['duration']

output:

    duration     bin
0      01:13  medium
1      01:09  medium
2      01:40    high
3      00:48     low
4      00:49     low
...      ...     ...
98     00:52     low
99     01:10  medium
100    01:05     low
101    01:09  medium
102    00:58     low

If you also want the boundaries:

df['bin'], boundaries = pd.cut(pd.to_timedelta(df['duration']+':00'),
                               bins=3, labels=['low', 'medium', 'high'],
                               retbins=True
                              )

print(boundaries)

output:

TimedeltaIndex(['0 days 00:47:56.880000',        '0 days 01:05:20',
                       '0 days 01:22:40',        '0 days 01:40:00'],
               dtype='timedelta64[ns]', freq=None)
Related