python - Pandas:针对时间序列数据生成直方图/数据透视图

标签 python pandas

我有一个数据框,前 5 行是:

indexed.head(5)
>>>>
                              SOURCE_SYSTEM              TRADE_ID
endtime
2013-09-12 15:04:44                 SystemA       PXXX86883150911
2013-09-12 17:25:07                 SystemB       PXXX66048140211
2013-09-12 17:25:07                 SystemY       PYYY66049140211
2013-09-12 17:25:08                 SystemZ       PZZZ34553220311
2013-09-12 17:25:09                 SystemZ       PAAA76226310311

注意,索引是按日期时间列。

我想生成两件事:
i) 按月(或其他时间长度)计算结果
ii) 按期间和第二列值(即数据透视表?)拆分的结果计数

我已经能够通过首先创建一个 Period 对象来实现第一个:

prng = pd.period_range(indexed.index.min(), indexed.index.max(),freq='M')

然后遍历它,沿途执行一种查找:

for r in prng:
    print ( str(r), len(indexed[str(r)]) )

哪个返回:

2013-09 8
2013-10 2
2013-11 4
2013-12 1069
2014-01 2242
2014-02 1338
2014-03 2567
2014-04 762
2014-05 1028
2014-06 1885
2014-07 4303
2014-08 879
2014-09 399
2014-10 6002
2014-11 622
2014-12 625

这就是我想要的 i)
问题是,有没有更简单的方法来做到这一点?我的第 ii 部分怎么样)也许有一种使用 groupby 和/或 pivot 的方法?我已经阅读了有关这些的文档,但不知何故我忽略了这一点。有什么建议吗?

最佳答案

您可以使用 df.resample 更轻松地完成 (i)如下图

import pandas as pd
from random import choice

N = 1024

dt = pd.date_range('1/1/2011', periods=N, freq='3H')
A = [choice('ABCD') for _ in range(N)]
B = [choice('WXYZ') for _ in range(N)]

df = pd.DataFrame(data={'A':A, 'B':B}, index=dt)
#                      A  B
# 2011-01-01 00:00:00  B  Z
# 2011-01-01 03:00:00  A  X
# 2011-01-01 06:00:00  B  Y
# 2011-01-01 09:00:00  D  W
# 2011-01-01 12:00:00  A  Z
# ...    

resampled = df.resample('M', how='count')
#              A    B
#2011-01-31  248  248
#2011-02-28  224  224
#2011-03-31  248  248
#2011-04-30  240  240
#2011-05-31   64   64

对于 (ii),您可以使用 pd.pivot_table ,一旦您创建了一个 month 列,该列包含您要转换的年月。

df['month'] = ['{}-{}'.format(y, m) for y, m in zip(df.index.year, df.index.month)]

pivot = pd.pivot_table(df, values='B', index='month', columns='A', aggfunc='count')
#A        A   B   C   D
#month
#2011-1  64  58  67  59
#2011-2  62  52  47  63
#2011-3  70  58  59  61
#2011-4  52  63  64  61
#2011-5  16  19  15  14

关于python - Pandas:针对时间序列数据生成直方图/数据透视图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27107807/

相关文章:

python - 可以在 Python 中创建非常大的元组吗?

python - 如果某些多个关键字匹配则过滤字符串

python - 如何从 pandas.DataFrame.info() 返回一个字符串

python - 使用 Pandas 的盈亏

python - Pandas:浓缩调查结果

python - Pandas 数据框 - 基于组的每列的总和

python - 在虚拟环境中使用 pip 构建 uwsgi 时出错

Python Bokeh 将附加参数发送到小部件事件处理程序

python - 带有正则表达式解析的新 Pandas 列

python-3.x - 使用数据帧作为另一个数据帧的查找