How do I extract only the hours from this:
TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:00', '0 days 00:00:00',
'0 days 00:00:00', '0 days 01:00:00', '0 days 01:00:00',
'0 days 01:00:00', '0 days 01:00:00', '0 days 02:00:00',
'0 days 02:00:00', '0 days 02:00:00', ... ],
dtype='timedelta64[ns]', freq=None)
I want only the hours and minutes stored in a column from my data frame.
CodePudding user response:
You can use datetime components.
import pandas as pd
from pandas import TimedeltaIndex
import datetime
df = pd.DataFrame(TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:00', '0 days 00:00:00',
'0 days 00:00:00', '0 days 01:00:00', '0 days 01:00:00',
'0 days 01:00:00', '0 days 01:00:00', '0 days 02:00:00',
'0 days 02:00:00', '0 days 02:00:00'],
dtype='timedelta64[ns]', freq=None))
df['hours'] = df[0].dt.components['hours']
Output df:
0 hours
0 0 days 00:00:00 0
1 0 days 00:00:00 0
2 0 days 00:00:00 0
3 0 days 00:00:00 0
4 0 days 01:00:00 1
5 0 days 01:00:00 1
6 0 days 01:00:00 1
7 0 days 01:00:00 1
8 0 days 02:00:00 2
9 0 days 02:00:00 2
10 0 days 02:00:00 2
CodePudding user response:
Use:
temp = ['0 days 00:00:00', '0 days 00:00:00', '0 days 00:00:00',
'0 days 00:00:00', '0 days 01:00:00', '0 days 01:00:00',
'0 days 01:00:00', '0 days 01:00:00', '0 days 02:00:00',
'0 days 02:00:00', '0 days 02:00:00']
import pandas as pd
df = pd.DataFrame(range(len(temp)), index = pd.to_timedelta(temp))
df.index.components['hours']
Output: