【发布时间】:2025-11-29 11:40:01
【问题描述】:
我正在尝试使用带有意外结果的字符串列表来分割由句点索引索引的 pandas 数据帧。
import pandas as pd
import numpy as np
idx = pd.period_range(1991,1993,freq='A')
df = pd.DataFrame(np.arange(9).reshape(3,3),index=idx)
print df.loc[['1991','1993'],:]
结果:
KeyError: "None of [['1991', '1993']] are in the [index]"
如果最后一行切换到:
print df.ix[['1991','1993'],:]
输出是
Out[128]:
0 1 2
1991 NaN NaN NaN
1993 NaN NaN NaN
如果我有一个周期索引而不是一个周期索引
idx = [str(year) for year in range(1991,1994)]
print df.loc[['1991','1993'],:]
那么输出如预期:
Out[127]:
0 1 2
1991 0 1 2
1993 6 7 8
所以我的问题是:如何使用周期索引对 pandas 数据帧进行切片?
【问题讨论】: