KeyError:'标签不在[索引]中'

2024-04-23 09:08:26 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,当我试图从数据帧访问值时,我一直收到以下错误。在

KeyError:'标签[2010Q3]不在[index]中。

我相信这是因为我的专栏采用了日期时间格式。我试着试着去串,但似乎没用。在

欢迎提出任何建议。在

谢谢。在

import pandas as pd
import numpy as np
from scipy.stats import ttest_ind

import time
from datetime import date

#Read in file, drop 1996-1999, and fill NAN with zeros
dfHousingData = pd.read_csv("City_Zhvi_AllHomes.csv")
dfHousingData = dfHousingData.drop(dfHousingData.columns[6:51],axis=1)
dfHousingData = dfHousingData.fillna(0)

#To use Perdiod index, create a seperate df with the dates, then grouby by 1/4 
dfTimeSerQs= dfHousingData.drop(dfHousingData.columns[0:6],axis=1)
dfTimeSerQs = dfTimeSerQs.groupby(pd.PeriodIndex(dfTimeSerQs.columns, freq='Q'), axis=1).mean()#.astype(str)
dfTimeSerQs.columns.strftime('%YQ%q')


#Drop the monthly data from the orgainal df and then recombine with the newly group data
dfHousingData = dfHousingData.drop(dfHousingData.columns[6:206],axis=1)
dfHousingData = pd.merge(dfHousingData,dfTimeSerQs, how = 'left',left_index=True,right_index=True)

#Apply dic and create index
dfHousingData['State'] = dfHousingData['State'].map(states)
dfHousingData.set_index(['State','RegionName'],inplace = True)

#Other feilds are not needed so drop
dfHousingData = dfHousingData.drop(dfHousingData.columns[0:4],axis=1)
#dfHousingData
dfHousingData.loc["Texas"].loc["Austin"].loc["2010Q3"]

Tags: columnsandthefromimporttrueindexwith