Chuck
Chuck

Reputation: 4892

How do I set a Series index to be DatetimeIndex instead of Index?

I execute the following in the Python REPL:

from pandas import read_csv

sales = read_csv('data.csv', header=None, parse_dates=True)
model1 = sales[sales['model'].eq('model1')].groupby('date')['qty').sum()

This gives me a series that looks like this:

date
2016-09-16    128
2016-09-17     34
2016-09-18      5
2016-09-19     19
2016-09-20     16
             ...
2019-10-03      1
2019-10-07      1
2019-10-11      1
2019-10-12      1
2019-10-14      1
Name: qty, Length: 863, dtype: int64

Now I want to group that by weeks and chart it, but when I try to resample it I get the following:

model1.resample('W')
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got instance of 'Index'

I thought the parse_dates=True would take care of that, but it hasn't. How do I tell pandas that the index column is a DatetimeIndex or convert it to one?

Upvotes: 0

Views: 129

Answers (1)

BENY
BENY

Reputation: 323226

Change the index by to_datetime

model1.index=pd.to_datetime(model1.index)

Upvotes: 1

Related Questions