Reputation: 298
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
Reputation: 712
if not do:
df['Date'] = pd.to_datetime(df['Date'])
Upvotes: 0
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