FaCoffee
FaCoffee

Reputation: 7909

How to slice pandas series with hour stamps as index?

This is my time series:

Time
00:00:00    24.364387
00:01:00    24.509357
00:02:00    24.484649
00:03:00    24.476170
00:04:00    24.458480
00:05:00    24.439327
Name: Vals, dtype: float64

How can I access the values based on a specific index interval? Such as myseries['00:02:00':'00:05:00']? I thought I had to turn them into time stamps (but hours, minutes, and seconds only).

So I have turned it into a data frame:

df=pd.DataFrame({'Time':myseries.index, 'Vals':myseries.vals})

If I type df.dtypes I get:

Vals            float64
Time            object
dtype: object

So Time is an object and not a datetime64[ns]. Then I try to do: df['Time'].dt.time but then I get: AttributeError: Can only use .dt accessor with datetimelike values.

If I try: df.loc['00:00:00':'00:05:00'], I only get my headers. What am I missing?

Upvotes: 0

Views: 858

Answers (3)

jujuBee
jujuBee

Reputation: 494

Here is my try:

import datetime as dt myseries = pd.DataFrame([24.364387,24.509357,24.484649,24.476170,24.458480,24.439327], index=pd.to_timedelta(['00:00:00','00:01:00','00:02:00','00:03:00','00:04:00','00:05:00'])) myseries.loc[dt.timedelta(minutes=1):dt.timedelta(minutes=3)]

Upvotes: 1

Pal
Pal

Reputation: 990

May be in your case, you don't need to convert at all. When you turn the series to dataframe, do this:

df = pd.DataFrame(myseries, columns=['Vals'])

Then try

df.loc['00:00:00':'00:05:00']

Upvotes: 1

Pal
Pal

Reputation: 990

You need to use the function pd.to_datetime(Series). Here is the code:

df.Time = pd.to_datetime(df.Time)

df.dtypes
Time     datetime64[ns]
Vals           float64
dtype: object

Upvotes: 1

Related Questions