Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

python - Reindexing a specific level of a MultiIndex dataframe

I have a DataFrame with two indices and would like to reindex it by one of the indices.

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

The reindexing goes as follows:

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

The last line gives the following error:

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

This is because the DataFrame index is a list of tuples:

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

Is it possible to reindex adj_close? By the way, if I don't convert the Panel object to a DataFrame using to_frame(), the reindexing works as it is. But it seems that Panel objects are deprecated...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're looking to reindex on a certain level, then reindex accepts a level argument you can pass -

adj_close.reindex(all_weekdays, level=0)

When passing a level argument, you cannot pass a method argument at the same time (reindex throws a TypeError), so you can chain a ffill call after -

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...