本文介绍了 pandas :有条件滚动计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来如下的系列:

I have a Series that looks the following:

   col
0  B
1  B
2  A
3  A
4  A
5  B

这是一个时间序列,因此索引按时间排序.

It's a time series, therefore the index is ordered by time.

对于每一行,我想计算该值连续出现了多少次,即:

For each row, I'd like to count how many times the value has appeared consecutively, i.e.:

输出:

   col count
0  B   1
1  B   2
2  A   1 # Value does not match previous row => reset counter to 1
3  A   2
4  A   3
5  B   1 # Value does not match previous row => reset counter to 1

我发现了2个相关问题,但是我不知道如何为每一行(如上)将这些信息写"为DataFrame中的新列.使用rolling_apply效果不佳.

I found 2 related questions, but I can't figure out how to "write" that information as a new column in the DataFrame, for each row (as above). Using rolling_apply does not work well.

相关:

按索引对熊猫数据帧上的连续事件进行计数

在熊猫数据框中查找连续的片段

推荐答案

我认为有一种很好的方法可以将@chrisb和@CodeShaman的解决方案结合在一起(因为有人指出,CodeShamans解决方案是对总数而不是连续的值进行计数).

I think there is a nice way to combine the solution of @chrisb and @CodeShaman (As it was pointed out CodeShamans solution counts total and not consecutive values).

  df['count'] = df.groupby((df['col'] != df['col'].shift(1)).cumsum()).cumcount()+1

  col  count
0   B      1
1   B      2
2   A      1
3   A      2
4   A      3
5   B      1

这篇关于 pandas :有条件滚动计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:05