无法使用这些索引器对<class'pandas.core.indexes.period.periodindex'=“”>进行切片索引

时间:2018-03-14 15:28:27

标签: python-3.x pandas

file_location3 = "F:/python/course1_downloads/City_Zhvi_AllHomes.csv"

housing = pd.read_csv(file_location3)    
housing.set_index(['State','RegionName'],inplace=True)
housing = housing.iloc[:, 49:]

housing = housing.groupby(pd.PeriodIndex(housing.columns,freq='Q'),axis=1).mean()

data = housing
data = data.iloc[:,'2008q3' : '2009q2']

我得到的错误是:

  

无法使用这些索引器'<class 'pandas.core.indexes.period.PeriodIndex'>[2008q3]进行切片索引   <'class 'str'>

现在我又收到了另一个错误

def price_ratio(row):
    return (row['2008q3'] - row['2009q2']) / row['2008q3']

data['up&down'] = data.apply(price_ratio, axis=1)

这给了我错误:KeyError: ('2008q3', 'occurred at index 0')

3 个答案:

答案 0 :(得分:1)

感谢@Scott帮助我, 在尝试了很多之后,我现在就开始工作了。

我将数据转换为DataFrame,然后执行上述操作,然后就可以了。

data = pd.DataFrame(housing)
data = data.loc[:,'2008q3':'2009q2']

data = data.reset_index()

data.columns = ['State', 'RegionName', '2008Q3', '2008Q4', '2009Q1', '2009Q2']
def price_ratio(difference):
return difference['2008Q3'] - difference['2009Q2']

data['Diff'] = data.apply(price_ratio,axis=1)

答案 1 :(得分:0)

尝试:

data.loc[:,'2008q3':'2009q2']

答案 2 :(得分:0)

像这样转换列:

data.columns = data.columns.astype(str)

将解决此问题。您可以形象地看到问题:

带有PeriodIndex:

>>> print(data.columns)

Index([2000Q1, 2000Q2, 2000Q3, 2000Q4, 2001Q1, 2001Q2, 2001Q3, 2001Q4, 2002Q1,
       2002Q2, 2002Q3, 2002Q4, 2003Q1, 2003Q2, 2003Q3, 2003Q4, 2004Q1, 2004Q2,
       2004Q3, 2004Q4, 2005Q1, 2005Q2, 2005Q3, 2005Q4, 2006Q1, 2006Q2, 2006Q3,
       2006Q4, 2007Q1, 2007Q2, 2007Q3, 2007Q4, 2008Q1, 2008Q2, 2008Q3, 2008Q4,
       2009Q1, 2009Q2, 2009Q3, 2009Q4, 2010Q1, 2010Q2, 2010Q3, 2010Q4, 2011Q1,
       2011Q2, 2011Q3, 2011Q4, 2012Q1, 2012Q2, 2012Q3, 2012Q4, 2013Q1, 2013Q2,
       2013Q3, 2013Q4, 2014Q1, 2014Q2, 2014Q3, 2014Q4, 2015Q1, 2015Q2, 2015Q3,
       2015Q4, 2016Q1, 2016Q2, 2016Q3],
      dtype='object')

设置data.columns = data.columns.astype(str)

之后
>>> print(data.columns)

Index(['2000Q1', '2000Q2', '2000Q3', '2000Q4', '2001Q1', '2001Q2', '2001Q3',
       '2001Q4', '2002Q1', '2002Q2', '2002Q3', '2002Q4', '2003Q1', '2003Q2',
       '2003Q3', '2003Q4', '2004Q1', '2004Q2', '2004Q3', '2004Q4', '2005Q1',
       '2005Q2', '2005Q3', '2005Q4', '2006Q1', '2006Q2', '2006Q3', '2006Q4',
       '2007Q1', '2007Q2', '2007Q3', '2007Q4', '2008Q1', '2008Q2', '2008Q3',
       '2008Q4', '2009Q1', '2009Q2', '2009Q3', '2009Q4', '2010Q1', '2010Q2',
       '2010Q3', '2010Q4', '2011Q1', '2011Q2', '2011Q3', '2011Q4', '2012Q1',
       '2012Q2', '2012Q3', '2012Q4', '2013Q1', '2013Q2', '2013Q3', '2013Q4',
       '2014Q1', '2014Q2', '2014Q3', '2014Q4', '2015Q1', '2015Q2', '2015Q3',
       '2015Q4', '2016Q1', '2016Q2', '2016Q3'],
      dtype='object')

您会知道它有效,因为data.loc['Texas'].loc['Austin'].loc['2002Q3']可以工作,而不必使用data.loc['Texas'].loc['Austin'].loc[pd.Period('2002Q3')]

如果您需要小写字母,例如2001q3而非2001Q3

data.columns = list(map(str.lower, data.columns.astype(str)))