如何计算一个值的外观,直到它变为另一个?

2024-03-28 22:04:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为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

有没有办法得到这个结果?你知道吗


Tags: 数据importnumpypandasdfvalueascount
2条回答

尽管@anky_91 answer是完美的,但一个简单的解决方案是创建一个函数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

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

相关问题 更多 >