重新索引 MultiIndex 数据帧的特定级别

Reindexing a specific level of a MultiIndex dataframe

我有一个带有两个索引的 DataFrame,我想用其中一个索引重新索引它。

from pandas_datareader import data
import matplotlib.pyplot as plt
import pandas as pd

# Instruments to download
tickers = ['AAPL']

# Online source one should use
data_source = 'yahoo'

# Data range
start_date = '2000-01-01'
end_date = '2018-01-09'

# Load the desired data
panel_data = data.DataReader(tickers, data_source, start_date, end_date).to_frame()
panel_data.head()

重建索引如下:

# Get just the adjusted closing prices
adj_close = panel_data['Adj Close']

# Gett all weekdays between start and end dates
all_weekdays = pd.date_range(start=start_date, end=end_date, freq='B')

# Align the existing prices in adj_close with our new set of dates
adj_close = adj_close.reindex(all_weekdays, method="ffill")

最后一行报错如下:

TypeError: '<' not supported between instances of 'tuple' and 'int'

这是因为 DataFrame 索引是一个元组列表:

panel_data.index[0]
(Timestamp('2018-01-09 00:00:00'), 'AAPL')

是否可以重建索引 adj_close?顺便说一下,如果我不使用 to_frame() 将 Panel 对象转换为 DataFrame,重新索引将按原样进行。但似乎 Panel 对象已被弃用...

如果您希望在某个 级别 上重建索引,那么 reindex 接受一个 level 参数,您可以传递 -

adj_close.reindex(all_weekdays, level=0)

当传递一个level参数时,你不能同时传递一个method参数(reindex抛出一个TypeError),所以你可以链接一个ffill 在 -

之后调用
adj_close.reindex(all_weekdays, level=0).ffill()