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

Bru*_*uno 5 python multi-index dataframe pandas reindex

我有一个带有两个索引的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()
Run Code Online (Sandbox Code Playgroud)

屏幕截图

重新索引如下:

# 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")
Run Code Online (Sandbox Code Playgroud)

最后一行给出以下错误:

TypeError: '<' not supported between instances of 'tuple' and 'int'
Run Code Online (Sandbox Code Playgroud)

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

panel_data.index[0]
Run Code Online (Sandbox Code Playgroud)
(时间戳('2018-01-09 00:00:00'),'AAPL')

是否可以重新编制索引adj_close?顺便说一句,如果我不使用将Panel对象转换为DataFrame to_frame(),则重新索引将按原样工作。但是似乎不建议使用Panel对象...

cs9*_*s95 6

如果您希望在某个级别上重新编制索引,则reindex可以接受一个level参数,您可以传递-

adj_close.reindex(all_weekdays, level=0)
Run Code Online (Sandbox Code Playgroud)

传递level参数时,不能同时传递method参数(reindex引发TypeError),因此可以ffill在-之后链接调用

adj_close.reindex(all_weekdays, level=0).ffill()
Run Code Online (Sandbox Code Playgroud)