我有一个这样的数据框
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()在行上循环,但是由于我有一个大数据集,所以它非常慢。 我还考虑过使用“ diff”,但我想不出一种简单的方法。谢谢
编辑: 预期的输出是这样的
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
答案 0 :(得分:2)
计算顺序模式是一个两步过程。首先,为每行构建一个序列,以表示在该行结束的模式:
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
根据需要进行处理,其中您希望模式在特定时期内开始,在整个期间内停止,等等。