微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个带有两个索引的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()

Screenshot

重新索引如下:

# 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)

传递级别参数时,不能同时传递方法参数(reindex会引发TypeError),因此可以在以下位置链接一个ffill调用

adj_close.reindex(all_weekdays, level=0).ffill()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐