使用 .loc 选择 DatetimeIndex 行范围(Pandas Python 3)

ano*_*non 5 python time-series python-3.x pandas datetimeindex

使用 DatetimeIndex 处理 pandas 系列。期望的结果是包含 .loc[] 函数指定范围内的所有行的数据帧。

当我尝试以下代码时:

aapl.index = pd.to_datetime(aapl.index)
print(aapl.loc[pd.Timestamp('2010-11-01'):pd.Timestamp('2010-12-30')])
Run Code Online (Sandbox Code Playgroud)

我回来了:

Empty DataFrame
Columns: [Open, High, Low, Close, Volume, ExDividend, SplitRatio, 
AdjOpen, AdjHigh, AdjLow, AdjClose, AdjVolume]
Index: []
Run Code Online (Sandbox Code Playgroud)

只是重申一下,我想要的结果是数据帧的子集,包含 (2010-11-01):(2010-12-30) 范围内的所有行。

jpp*_*jpp 5

看来您需要将索引转换为datetime,然后使用标准索引/切片表示法。

import pandas as pd, numpy as np

df = pd.DataFrame(list(range(365)))

# these lines are for demonstration purposes only
df['date'] = pd.date_range('2010-1-1', periods=365, freq='D').astype(str)
df = df.set_index('date')

df.index = pd.to_datetime(df.index)

res = df[pd.Timestamp('2010-11-01'):pd.Timestamp('2010-11-10')]

#               0
# date           
# 2010-11-01  304
# 2010-11-02  305
# 2010-11-03  306
# 2010-11-04  307
# 2010-11-05  308
# 2010-11-06  309
# 2010-11-07  310
# 2010-11-08  311
# 2010-11-09  312
# 2010-11-10  313
Run Code Online (Sandbox Code Playgroud)


Sco*_*ton 4

国际大学学院:

import pandas_datareader as web
aapl = web.get_data_yahoo('aapl')

aapl.loc['2010-11-01':'2010-12-30']
Run Code Online (Sandbox Code Playgroud)

使用部分字符串索引和切片。