熊猫通过多索引提取数据

时间:2019-12-03 14:55:12

标签: python pandas multi-index

我正在从网站上将following data读入DataFrame。

我使用以下脚本清理数据:

import pandas as pd

fpath = r'https://www.apra.gov.au/annual-fund-level-superannuation-statistics'
xl_data = pd.read_excel(fpath,sheet_name=['Table 3','Table 9'])
returns = xl_data['Table 3']
returns.columns = returns.loc[2]
returns = returns.iloc[6:,:]
returns['Period'] = pd.to_datetime( returns['Period'])
ror_col = 'One-year\nrate of return'
returns = returns[ returns[ror_col]!='*']
has_returns = returns[ror_col].dropna().index
returns = returns.loc[has_returns].copy()
returns[ror_col]=returns[ror_col].astype(float)
returns_multi_index = returns.copy()
returns_multi_index.index = returns_multi_index[['Period','Fund name']]
returns_multi_index = returns_multi_index[[ror_col]]

returns_multi_index.loc[(slice(None),slice('Alcoa of Australia Retirement Plan')),:] #This line crashes

通常,我要选择某个计划的所有日期和所有列。

OR

我想要一个特定的日期,但是要用于所有计划和所有列。

我以前使用过面板,但是由于弃用了面板,我还没有完全采用新的多索引方法。

我并不喜欢使用切片,而是试图遵循this tutorial的指导。

我得到的当前错误是:

pandas\index.pyx in pandas.index.IndexEngine.get_indexer_non_unique (pandas\index.c:5817)()

TypeError: unhashable type

1 个答案:

答案 0 :(得分:0)

问题是这一行:

returns_multi_index.index = returns_multi_index[['Period','Fund name']]
#Index([              (2018-06-30 00:00:00, 'Alcoa of Australia Retirement Plan'),
#      ...
#      dtype='object', length=4360)

它不会创建多索引,而是创建一个元组的常规索引。您应该改用:

returns_multi_index.set_index(['Period','Fund name'],inplace=True)
#MultiIndex([('2018-06-30',               'Alcoa of Australia Retirement Plan'),
#           ...
#           names=['Period', 'Fund name'], length=4360)

此外,multiIndex切片需要对索引进行完全lexsorted,这可以通过以下方式实现:

returns_multi_index.sort_index(inplace=True)