如何计算一个值的出现,直到它更改为另一个值?

时间:2019-06-19 07:18:18

标签: python pandas dataframe

我有一个名为df的熊猫数据框。在此数据帧中,我得到了一个名为value的变量。我想添加一个变量以计数相同值的出现,直到它更改为另一个值为止。我们将此新变量称为count

我的数据框如下所示:

import pandas as pd
import numpy as np

ar = np.array([[1], [1], [2],[2], [3], [3], [1], [1], [2], [2]])
df = pd.DataFrame(ar,  columns = ['Value'])

print(df)

   Value
0      1
1      1
2      2
3      2
4      3
5      3
6      1
7      1
8      2
9      2

我尝试了以下代码:

df['count'] = df.groupby('Value').cumcount() + 1

哪个返回:

print(df)
   Value  count
0      1      1
1      1      2
2      2      1
3      2      2
4      3      1
5      3      2
6      1      3
7      1      4
8      2      3
9      2      4

我希望这样:

print(df)
   Value  count
0      1      1
1      1      2
2      2      1
3      2      2
4      3      1
5      3      2
6      1      1
7      1      2
8      2      1
9      2      2

有没有办法获得输出?

2 个答案:

答案 0 :(得分:2)

IIUC,使用:

df=df.assign(count=df.groupby(df.Value.ne(df.Value.shift()).cumsum()).cumcount().add(1))

   Value  count
0      1      1
1      1      2
2      2      1
3      2      2
4      3      1
5      3      2
6      1      1
7      1      2
8      2      1
9      2      2

位置:

print(df.Value.ne(df.Value.shift()))

0     True
1    False
2     True
3    False
4     True
5    False
6     True
7    False
8     True
9    False
Name: Value, dtype: bool

答案 1 :(得分:0)

尽管@ anky_91答案是完美的,但一个幼稚的解决方案是不使用他的答案中讨论的方法来创建函数count_upto

def count_upto(series):
  count = np.ones(len(series),np.int32)
  for i in range(1,len(series)):
    word=series[i]
    if word == series[i-1]:
      count[i] = count[i-1] +1
  return count

df['count']=count_upto(df.Value.values)
print(df)
>>>
  Value c
0   1   1
1   1   2
2   1   3
3   2   1
4   3   1
5   3   2
6   1   1
7   1   2
8   2   1
9   2   2