Skip to main content
 首页 » 编程设计

python之Pandas unstack 不起作用

2025年05月04日8zhengyun_ustc

最初我有 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 

我想绘制某种类型的 Action 数量与一天的对比

因此我使用 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