计算数据帧中数字连续出现的次数 [英] Counting the number of consecutive occurences of numbers in dataframe

查看:49
本文介绍了计算数据帧中数字连续出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 1s 和 0s 的虚拟列的数据框,我想为每一行计算 1s 或 0s 发生的次数,每次从 0 开始,向上计数 1s 并向下计数0s 我在下面有一个例子:

I have a dataframe with a dummy column that contains 1s and 0s and I would like to count for each row how many times the 1s or 0s have occurred, starting at 0 every time, and counting up for 1s and counting down for 0s I have an example below:

 import pandas as pd
 df = pd.DataFrame({'Dummy': [0, 0, 1, 1, 1, 0, 1, 1, 1, 1],
        'Counter': [-1, -2, 1, 2, 3, -1, 1, 2, 3, 4]})

推荐答案

我们来试试:

blocks = df.Dummy.diff().ne(0).cumsum()
counters = df.groupby(blocks).cumcount() + 1
df['Counter'] = np.where(df['Dummy']==0, -1, 1) * counters

输出:

   Dummy  Counter
0      0       -1
1      0       -2
2      1        1
3      1        2
4      1        3
5      0       -1
6      1        1
7      1        2
8      1        3
9      1        4

这篇关于计算数据帧中数字连续出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆