python-3.x - 熊猫计算跨行条件的每月发生次数
问题描述
我有一个这样的数据框
oper_status
2012-01-01 00:26:54.250 0
2012-01-01 12:11:54.250 1
2012-01-01 13:57:54.250 2
2012-01-02 00:16:54.250 0
2012-01-02 14:26:54.250 1
2012-01-02 17:20:54.250 0
2012-01-04 08:21:54.250 0
2012-01-04 15:34:54.250 1
2012-01-04 19:45:54.250 0
2012-01-05 01:00:54.250 0
2012-01-05 12:46:54.250 1
2012-01-05 20:27:54.250 2
(...) (...)
我想计算每个月有多少次我有这种模式的连续值:0,1,2。我尝试使用 iterrows() 对行进行循环,但它非常慢,因为我有一个大数据集。我也考虑过使用“差异”,但我想不出一个简单的方法来做到这一点。谢谢
编辑:预期的输出是这样的
count
time
2012-03-31 244
2012-04-30 65
2012-05-31 167
2012-06-30 33
2012-07-31 187
... ...
2013-05-31 113
2013-06-30 168
2013-07-31 294
2013-08-31 178
2013-09-30 65
解决方案
计算顺序模式是一个两步过程。首先,为每一行构建一个序列,表示在该行结束的模式:
df['seq'] = df.order_status.astype(str).shift(periods=0) + '-' +
df.order_status.astype(str).shift(periods=1) + '-' +
df.order_status.astype(str).shift(periods=2)
date order_status seq
0 2012-01-01 00:26:54.250 0 NaN
1 2012-01-01 12:11:54.250 1 NaN
2 2012-01-01 13:57:54.250 2 2-1-0
3 2012-01-02 00:16:54.250 0 0-2-1
4 2012-01-02 14:26:54.250 1 1-0-2
5 2012-01-02 17:20:54.250 0 0-1-0
6 2012-01-04 08:21:54.250 0 0-0-1
7 2012-01-04 15:34:54.250 1 1-0-0
8 2012-01-04 19:45:54.250 0 0-1-0
9 2012-01-05 01:00:54.250 0 0-0-1
10 2012-01-05 12:46:54.250 1 1-0-0
11 2012-01-05 20:27:54.250 2 2-1-0
然后,过滤到仅正确的序列并聚合到您想要的级别:
df['month'] = df.date.dt.month
df[df.seq == '2-1-0'].groupby("month").month.count()
month
1 2
根据需要进行更改以处理您希望模式在某个时期开始、在那里停止、完全在其中等的情况......
推荐阅读
- karate - 我们可以配置 karate.waitForHttp(url)
- python - 解析 json 文件以获取其中每个日期的特定字段
- java - “E/AndroidRuntime: FATAL EXCEPTION: main”当我在循环中使用 addView
- mysql - 如何动态创建具有多个 WHERE LIKE 和 OR 的 mysql 查询?
- python - 我如何检测关键字但获取整个链接?
- flutter - 使用 socket_io_client ^0.9.12 在 Flutter 中配置 socketIO 连接时出错
- algorithm - 二叉索引树:为什么“i + lowBit(i)”有效?
- react-admin - 是否有不支持分页、过滤或搜索的 API 的数据提供者?
- spring-boot - 为什么使用springboot下载zip时多次调用接口?
- android - Android Hilt 向 Activity 实现的视图模型注入接口