I have a datetime
issue where I am trying to match up a dataframe
with dates as index values.
For example, I have dr
which is an array of numpy.datetime
.
dr = [numpy.datetime64('2014-10-31T00:00:00.000000000'),
numpy.datetime64('2014-11-30T00:00:00.000000000'),
numpy.datetime64('2014-12-31T00:00:00.000000000'),
numpy.datetime64('2015-01-31T00:00:00.000000000'),
numpy.datetime64('2015-02-28T00:00:00.000000000'),
numpy.datetime64('2015-03-31T00:00:00.000000000')]
Then I have dataframe with returndf
with dates as index values
print(returndf)
1 2 3 4 5 6 7 8 9 10
10/31/2014 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
11/30/2014 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
Please ignore the missing values
Whenever I try to match date in dr
and dataframe returndf
, using the following code for just 1 month returndf.loc[str(dr[1])]
,
I get an error
KeyError: 'the label [2014-11-30T00:00:00.000000000] is not in the [index]'
I would appreciate if someone can help with me on how to convert numpy.datetime64('2014-10-31T00:00:00.000000000')
into 10/31/2014
so that I can match it to the data frame index value.
Thank you,
Your index for returndf
is not a DatetimeIndex
. Make is so:
returndf = returndf.set_index(pd.to_datetime(returndf.index))
Your dr
is a list of Numpy datetime64
objects. That bothers me:
dr = pd.to_datetime(dr)
Your sample data clearly shows that the index of returndf
does not include all the items in dr
. In that case, use reindex
returndf.reindex(dr) 1 2 3 4 5 6 7 8 9 10 2014-10-31 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2014-11-30 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2014-12-31 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2015-01-31 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2015-02-28 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2015-03-31 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.