熊猫的 Bug/功能,其中按日期筛选的多索引数据帧在提取日期索引级别时返回所有未筛选的日期



这是最容易用代码解释的,所以这里是 - 想象一下 ipython/jupyter notebooks 中的命令:

from io import StringIO
import pandas as pd
test = StringIO("""Date,Ticker,x,y
2008-10-23,A,0,10
2008-10-23,B,1,11
2008-10-24,A,2,12
2008-10-24,B,3,13
2008-10-25,A,4,14
2008-10-25,B,5,15
2008-10-26,A,6,16
2008-10-26,B,7,17
""")
# Multi-index by Date and Ticker
df = pd.read_csv(test, index_col=[0, 1], parse_dates=True)
df
# Output to the command line
x   y
Date       Ticker       
2008-10-23 A       0  10
B       1  11
2008-10-24 A       2  12
B       3  13
2008-10-25 A       4  14
B       5  15
2008-10-26 A       6  16
B       7  17
ts = pd.Timestamp(2008, 10, 25)
# Filter the data by Date >= ts
filtered_df = df.loc[ts:]
# output the filtered data
filtered_df
x   y
Date       Ticker       
2008-10-25 A       4  14
B       5  15
2008-10-26 A       6  16
B       7  17
# Get all the level 0 data (i.e. the dates) in the filtered dataframe
dates = filtered_df.index.levels[0]
# output the dates in the filtered dataframe:
dates
DatetimeIndex(['2008-10-23', '2008-10-24', '2008-10-25', '2008-10-26'], dtype='datetime64[ns]', name='Date', freq=None)
# WTF!!!???  This was ALL of the dates in the original dataframe - I asked for the dates in the filtered dataframe!
# The correct output should have been:
DatetimeIndex(['2008-10-25', '2008-10-26'], dtype='datetime64[ns]', name='Date', freq=None)

很明显,在多索引中,当一个筛选时,过滤后的数据帧的索引会保留原始数据帧的所有索引,但仅在查看整个数据帧时显示可见索引。 但是,当按索引级别查看数据时,似乎存在一个错误(以某种方式具有功能?(,其中整个索引(包括不可见索引(用于执行我为提取上述代码中的所有日期所做的操作。

这实际上在MultiIndex的用户指南中进行了解释(强调(:

MultiIndex 保留索引的所有已定义级别,即使它们实际上并未使用。在对索引进行切片时,您可能会注意到这一点。...这样做是为了避免重新计算级别,以使切片具有高性能。如果只想查看已使用的级别,可以使用get_level_values()方法。

在您的情况下:

>>> filtered_df.index.get_level_values(0)
DatetimeIndex(['2008-10-25', '2008-10-25', '2008-10-26', '2008-10-26'], dtype='datetime64[ns]', name='Date', freq=None)

这是你所期望的。

最新更新