熊猫:PeriodIndex之后查询

时间:2018-08-04 16:56:33

标签: python pandas

如何在groupby之后然后在PeriodIndex之后查询列。这是我第一个回答的问题的后续行动。

Link to the problem.

我无法查询以句点命名的列。例如:

housing['2008Q3']

这是返回的错误:

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4433)()

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4279)()

pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13742)()

pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13696)()

KeyError: '2008Q3'

我学到的东西:当我列出我的专栏时,它返回:

['State',
 'RegionName',
 Period('2008Q3', 'Q-DEC'),
 Period('2008Q4', 'Q-DEC'),
 Period('2009Q1', 'Q-DEC'),
 Period('2009Q2', 'Q-DEC'),
 Period('2009Q3', 'Q-DEC'),
 Period('2009Q4', 'Q-DEC')]

我想取消句点,只是将它们设为字符串。 我尝试过

housing[Period('2009Q4', 'Q-DEC')]

但是让我看到这个错误:

name 'Period' is not defined

哈哈

1 个答案:

答案 0 :(得分:1)

您可以先将列转换为字符串,如下所示:

housing.columns=housing.columns.to_series().astype(str)

然后您可以通过其str名称访问列:

housing['2008Q3'].head()

0    499766.666667
1    469500.000000
2    232000.000000
3    116933.333333
4    193766.666667
Name: 2008Q3, dtype: float64
相关问题