【发布时间】:2018-06-25 05:55:32
【问题描述】:
我有一个具有以下形式的 pandas 数据框:
Response
Time
2018-01-14 00:00:00 201
2018-01-14 00:00:00 400
2018-01-14 00:00:00 200
2018-01-14 00:00:00 400
2018-01-14 00:00:00 200
时间是索引列。
我想获得随时间(15 分钟间隔)分组的响应图表,所以我写了以下内容:
for ind, itm in enumerate(df_final['Response'].unique()):
ax=df_final[df_final['Response'] == itm].groupby(pd.Grouper(key='Time',freq='15Min')).count().plot(kind='bar', figsize=(15,10), title="Response Codes")
ax.legend(["Response: {}".format(itm)])
这适用于已折旧的 TimeGrouper,其中上述代码中的第二行是:
ax=df_final[df_final['Response'] == item].groupby(pd.TimeGrouper(freq='15Min')).count().plot(kind='bar', figsize=(15,10), title="Response Codes")
但是当我运行 Grouper 代码时出现错误:
KeyError: 'The grouper name Time is not found'
我还将键更改为 df_final.index.name 但这也导致 KeyError: 'The grouper name Time is not found'
索引是 index 类型,但我将其更改为 DatetimeIndex:
type(df_final.index)
pandas.core.indexes.datetimes.DatetimeIndex
更改索引类型并运行后:
ax=df_final[df_final['Response'] == itm].groupby(pd.Grouper(key=df_final.index, freq='15Min')).count().plot(kind='bar', figsize=(15,10), title="Response Codes")
我明白了:
TypeError: unhashable type: 'DatetimeIndex'
我显然遗漏了一些东西。我在这里做错了什么?
只是为了显示索引是什么,df_final.index 给出了结果:
DatetimeIndex(['2018-01-14 00:00:00', '2018-01-14 00:00:00',
'2018-01-14 00:00:00', '2018-01-14 00:00:00',
'2018-01-14 00:00:00', '2018-01-14 00:00:00',
'2018-01-14 00:00:00', '2018-01-14 00:00:00',
'2018-01-14 00:00:00', '2018-01-14 00:00:00',
...
'2018-01-15 00:00:00', '2018-01-15 00:00:00',
'2018-01-15 00:00:00', '2018-01-15 00:00:00',
'2018-01-15 00:00:00', '2018-01-15 00:00:00',
'2018-01-15 00:00:00', '2018-01-15 00:00:00',
'2018-01-15 00:00:00', '2018-01-15 00:00:00'],
dtype='datetime64[ns]', name='Time', length=48960011, freq=None)
在 jezrael 的帮助下进行了一些调查后,看起来问题出在情节方法上。我将代码分解为:
for ind, itm in enumerate(df_final['Response'].unique()):
ax=df_final[df_final['Response'] == itm].groupby(pd.Grouper(level='Time', freq='15Min')).count()
ax.plot(kind='bar', figsize=(15,10), title="Response Codes")
情节线出现的错误是:
~/anaconda2/envs/py3env/lib/python3.6/site-packages/pandas/plotting/_core.py in __init__(self, data, kind, by, subplots, sharex, sharey, use_index, figsize, grid, legend, rot, ax, fig, title, xlim, ylim, xticks, yticks, sort_columns, fontsize, secondary_y, colormap, table, layout, **kwds)
98 table=False, layout=None, **kwds):
99
--> 100 _converter._WARN = False
101 self.data = data
102 self.by = by
NameError: name '_converter' is not defined
我不知道我是否做错了什么,或者 matplotlib 中是否有错误,但这是我发现自己坚持的立场。上一行 ax 按预期显示计数和次数
【问题讨论】:
标签: python python-3.x pandas