2016-02-26 39 views
0

假设我有事件数据,如:如何从重采样列创建数据透视表?

ts,uid 
2016-02-13 20:18:03.000001 UTC,5236965070 
2016-02-13 23:05:08 UTC,2834437228 
2016-02-13 23:13:00.000032 UTC,2206245130 
2016-02-13 22:45:07.000004 UTC,1539535012 
2016-02-13 23:47:44 UTC,3431025028 
2016-02-13 16:42:16.000001 UTC,810825324 
2016-02-13 22:37:14 UTC,2625355144 
2016-02-14 00:31:52.000009 UTC,24815453 
2016-02-12 06:43:40.000007 UTC,3895095040 
2016-02-14 00:09:04 UTC,715095136 
... 

如何创建UID的数据透视表,一个小时内,事件计数?我想这样做

DF.groupby([ 'UID',pandas.TimeGrouper(键= 'TS',FREQ = 'H')],排序=假).Count之间()

但我得到了ValueError: items in new_categories are not the same as in old categories。我怎样才能使它工作?是使用pivot还是pivot_table更好的方法?

回答

1

这是更好地利用dt.hour时间戳访问小时(如果你的列是不是已经的日期时间,它使用pd.to_datetime转换):

In [90]: df.groupby([df.uid,df.ts.dt.hour]).count() 
Out[90]: 
       ts 
uid  ts 
24815453 0 1 
715095136 0 1 
810825324 16 1 
1539535012 22 1 
2206245130 23 1 
2625355144 22 1 
2834437228 23 1 
3431025028 23 1 
3895095040 6 1 
5236965070 20 1 

注意,GROUPBY“消耗” UID列;如果你想避免这种情况,你可以使用as_index = False