Doo Hyun Shin
Doo Hyun Shin

Reputation: 298

Slicing dataframe by Date is done but inputting the sliced to a variable is not working

It was done with slicing dataframe through datetime objects. But the problem is that the sliced data are not input to a variable.

The variable should be as dataframe. Of course, when I sliced the dataframe, the type of the sliced was dataframe.

df.tail()
Out[37]: 
              Price     Open     High  ...   Change %  A Day %  OC %
Date                                   ...                          
2019-07-10  13435.0  13427.5  13545.0  ...       0.04     1.18  0.06
2019-07-11  13455.0  13432.5  13647.5  ...       0.15     1.75  0.17
2019-07-12  13552.5  13457.5  13645.0  ...       0.72     2.11  0.71
2019-07-15  13545.0  13557.5  13662.5  ...      -0.06     2.65 -0.09
2019-07-16  13440.5  13552.5  13594.0  ...      -0.77     1.23 -0.83


import datetime as dt
df.set_index('Date', inplace=True)
start = dt.datetime(2019,1,1)
end = dt.datetime.today().strftime('%Y-%m-%d')

df[start:end]

the code df[start:end] just works fine. However, when I try variable = df[start:end] the console shows

"KeyError: 'Date'"

I want the dataframe df[start:end] to be input to a variable.

Thanks in advance.

Upvotes: 0

Views: 138

Answers (2)

Gustavo Gradvohl
Gustavo Gradvohl

Reputation: 712

It worked on my end, one thing you can try is to make sure you Date is in the correct format.

if not do:

df['Date']  = pd.to_datetime(df['Date'])

enter image description here

Upvotes: 0

rrcal
rrcal

Reputation: 3752

Your start and end variables are likely not the same format:

start = dt.datetime(2019,1,1) #datetime
end = dt.datetime.today().strftime('%Y-%m-%d') #str

For the indexing to work as expected, one suggestion would be to also transform start to string:

start = dt.datetime(2019,1,1).strftime('%Y-%m-%d') #str
end = dt.datetime.today().strftime('%Y-%m-%d') #str

This way, and assuming your dates on index are also a str, your command should work:

# if index is datetime, convert to string:
# df.index = df.index.apply(lambda x: .strftime('%Y-%m-%d'))

df[start:end]

Upvotes: 1

Related Questions