Counting the number of consecutive occurences of numbers in dataframe

前提是你 提交于 2021-01-27 19:23:03

问题


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]})

回答1:


Let's try:

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

Output:

   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


来源:https://stackoverflow.com/questions/64128616/counting-the-number-of-consecutive-occurences-of-numbers-in-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!