尝试命名多个索引获取密钥错误

问题描述 投票:1回答:1

早上好,

我正在使用python 3.6。我正在尝试命名我的索引(请参阅下面的代码中的最后一行),因为我打算加入另一个DataFrame。 DataFrame应该是多索引的。索引是前两列('currency'和'rtdate')和数据

                      rate
   AUD  2010-01-01    0.897274
        2010-02-01    0.896608
        2010-03-01    0.895943
        2010-04-01    0.895277
        2010-05-01    0.894612

这是我正在运行的代码:

import pandas as pd
import numpy as np
import datetime as dt

df=pd.read_csv('file.csv',index_col=0)
df.index = pd.to_datetime(df.index)
new_index = pd.date_range(df.index.min(),df.index.max(),freq='MS')
df=df.reindex(new_index)
df=df.interpolate().unstack()
rate = pd.DataFrame(df)
rate.columns = ['rate']
rate.set_index(['currency','rtdate'],drop=False)

运行此throw是一条错误消息:

KeyError: 'currency'

我错过了什么

谢谢你的帮助

python-3.x pandas dataframe
1个回答
0
投票

我认为你需要首先使用MultiIndex设置rename_axis级别的名称,然后使用reset_index来设置MultiIndex的列:

所以你最终得到这个:

rate = df.interpolate().unstack().set_axis(('currency','rtdate')).reset_index()

而不是这个:

df=df.interpolate().unstack()
rate = pd.DataFrame(df)
rate.columns = ['rate']
rate.set_index(['currency','rtdate'],drop=False)
© www.soinside.com 2019 - 2024. All rights reserved.