[英]Python Pandas Datetime and dataframe indexing issue
I have a datetime
issue where I am trying to match up a dataframe
with dates as index values. 我有一个
datetime
问题,我试图将日期作为索引值的dataframe
进行匹配。
For example, I have dr
which is an array of numpy.datetime
. 例如,我有
dr
,它是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 然后我有带有日期作为索引值的
returndf
数据returndf
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])]
, 每当我尝试匹配
dr
和returndf
中的日期时,仅使用以下代码1个月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. 如果有人可以帮助我将
numpy.datetime64('2014-10-31T00:00:00.000000000')
转换为numpy.datetime64('2014-10-31T00:00:00.000000000')
10/31/2014
以便将其与数据帧索引值进行匹配,我将不胜感激。
Thank you, 谢谢,
Your index for returndf
is not a DatetimeIndex
. 您的
returndf
索引不是DatetimeIndex
。 Make is so: Make是这样的:
returndf = returndf.set_index(pd.to_datetime(returndf.index))
Your dr
is a list of Numpy datetime64
objects. 您的
dr
是Numpy datetime64
对象的列表。 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
. 您的样本数据清楚地表明,
returndf
的索引并不包括dr
所有项目。 In that case, use reindex
在这种情况下,请使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.