最初,我的 DF 包含 1 列使用 DatetimeIndex 索引的操作:
In [371]: dates
2013-12-29 19:21:00 action1
2013-12-29 19:21:01 action2
2013-12-29 19:21:11 action1
2013-12-29 19:21:13 action2
...
In [372]: dates.index
Out[372]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-12-29 19:02:27, ..., 2014-01-13 16:30:31]
Length: 108957, Freq: None, Timezone: None
我想绘制特定类型的操作数量与日期的关系
所以我按日期对操作进行分组,使用agg
grouped = dates.groupby([dates.index.to_period(freq = 'D'), 'actiontype']).agg(len)
这给了我多索引系列:
...
2014-01-13 action1 435
action2 2067
..
2014-01-14 action1 455
action2 1007
...
这似乎正是我所需要的。
但当尝试时unstack
该系列摆脱了 MultiIndex 并绘制了我的数据,并得到了错误:
In [379]: grouped.unstack()
ValueError: freq not specified and cannot be inferred from first element
我在这里犯了什么错误?谢谢。
如果您需要使用.unstack()
它不适用于该多重索引,然后从非索引数据开始
index mydate action
0 2000-12-29 00:10:00 action1
1 2000-12-29 00:20:00 action2
2 2000-12-29 00:30:00 action2
3 2000-12-29 00:40:00 action1
4 2000-12-29 00:50:00 action1
5 2000-12-31 00:10:00 action1
6 2000-12-31 00:20:00 action2
7 2000-12-31 00:30:00 action2
你可以做类似的事情
df['day'] = df['mydate'].apply(lambda x: x.split()[0])
counts = df.groupby(['day', 'action']).agg(len)
基本上你忘记了日期时间是一个日期时间,你只是将它保留为字符串,并且只保留日期,丢弃时间。现在 pandas 在时间维度上会很愚蠢,但是counts.unstack()
给你
mydate
action action1 action2
day
2000-12-29 3 2
2000-12-31 1 2
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)