我想用一个包含 pd.date_range 的变量来分割我的 pandas 数据框,但它为我的数据返回 Nan

I want to slice my pandas data frame with a variable that contains a pd.date_range, but it is returning Nan for my data

我已从雅虎财经加载数据,其中包括标题日期、开盘价、最高价、最低价、收盘价、成交量、调整收盘价。日期是我的数据框索引,我希望能够使用索引(日期)对这些数据进行排序。

变量 month 将给出我需要的日期数组,并将打印出来。问题是我的数据得到了 Nan 值。

from pandas_datareader import data as dreader
import pandas as pd

df = pd.read_csv("cde_data.csv",index_col='Date')
month = pd.date_range('2010-08-01','2016-08-01',freq='m')

print(df.ix[month.values])

这是我得到的输出(我只发布了前 4 行以保存 space)

            Open  High  Low  Close  Volume  Adj Close
Date
2010-08-31   NaN   NaN  NaN    NaN     NaN        NaN

2010-09-30   NaN   NaN  NaN    NaN     NaN        NaN

2010-10-31   NaN   NaN  NaN    NaN     NaN        NaN

2010-11-30   NaN   NaN  NaN    NaN     NaN        NaN

这个 df.head()

              Open    High     Low   Close  Volume   Adj Close
Date
1990-04-12  26.875  26.875  26.625  26.625    6100  250.576036
1990-04-16  26.500  26.750  26.375  26.750     500  251.752449
1990-04-17  26.750  26.875  26.750  26.875    2300  252.928863
1990-04-18  26.875  26.875  26.500  26.625    3500  250.576036
1990-04-19  26.500  26.750  26.500  26.750     700  251.752449

按任意键继续。 . .

您的索引不是日期时间类型而是对象类型。使用前转换它:

df = df.reset_index()
df.Date = pd.to_datetime(df.Date)
df = df.set_index('Date')