0
$\begingroup$

I've a time series dataset which I thrown into Pandas. I have later converted the Date column into a DateTime column and then transformed to an index. To here, everything is ok.

Problems arise when I try to segment the data by day. If I do something like df['2020-05-20'] python thrown an exception. If I limit the selection to Year and Month everything is ok.

I thought initially this could have due to multiple rows with the same index, but this is not the case (I've tested with a unique date serie.

See below a reproducible example:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.array([['2019-05-26','4'],['2019-06-02','4'],['2019-06-09','2'],['2019-06-16','3'],['2019-06-23','2'],['2019-06-30','3'],['2019-07-07','4'],['2019-07-14','4'],['2019-07-21','3'],['2019-07-28','2'],['2019-08-04','5'],['2019-08-11','4'],['2019-08-18','4'],['2019-08-25','3'],['2019-09-01','5'],['2019-09-08','4'],['2019-09-15','4'],['2019-09-22','3'],['2019-09-29','4'],['2019-10-06','3'],['2019-10-13','7'],['2019-10-20','4'],['2019-10-27','4'],['2019-11-03','3'],['2019-11-10','4'],['2019-11-17','3'],['2019-11-24','4'],['2019-12-01','3'],['2019-12-08','2'],['2019-12-15','2'],['2019-12-22','1'],['2019-12-29','3'],['2020-01-05','4'],['2020-01-12','5'],['2020-01-19','7'],['2020-01-26','23'],['2020-02-02','19'],['2020-02-09','9'],['2020-02-16','9'],['2020-02-23','52'],['2020-03-01','26'],['2020-03-08','30'],['2020-03-15','46'],['2020-03-22','62'],['2020-03-29','100'],['2020-04-05','87'],['2020-04-12','56'],['2020-04-19','55'],['2020-04-26','45'],['2020-05-03','45'],['2020-05-10','41'],['2020-05-17','29']]), columns=['Week', 'Volume'])

df['Week'] = pd.to_datetime(df['Week'])
df.set_index('Week', inplace = True)

df.index

At this stage, with your index converted to a DateTimeIndex, both the following statements fail:

df['05-26-2019']
# or
df['2019-05-26']

But a query by month alone with either df['May 2019'] or df['05-2019'] work fine.

Any idea why I can't segment also using the day?

$\endgroup$
2
  • $\begingroup$ A running example with the error details would be nice to see please. $\endgroup$ May 20, 2020 at 22:12
  • $\begingroup$ @BlackCurrant added above. $\endgroup$ May 21, 2020 at 6:40

1 Answer 1

0
$\begingroup$

Solution-

df.loc['05-26-2019']

Borrowed from-

https://stackoverflow.com/questions/36871188/how-to-access-pandas-dataframe-datetime-index-using-strings

$\endgroup$
2
  • $\begingroup$ I've clearly searched for the wrong things :) Thanks $\endgroup$ May 21, 2020 at 8:13
  • $\begingroup$ happens to all of us. :-) $\endgroup$ May 21, 2020 at 8:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.