gpt4 book ai didi

python - Pandas :根据另一列增加或重置计数

转载 作者:太空宇宙 更新时间:2023-11-03 23:57:46 25 4
gpt4 key购买 nike

我有一个代表分数时间序列的 Pandas DataFrame。我想根据以下标准使用该分数来计算 CookiePoints 列:

  • 每当分数比之前的分数有所提高时,就会给出一个 CookiePoint。
  • 每次分数没有提高时,将所有CookiePoints作为惩罚带走(CookiePoints设置为0)。
  • 3 Cookiepoints 可以换取 Cookie。因此,达到 3 后,CookiePoints 计数应为 1(如果分数更高)或 0(如果分数不高)。

示例如下:

Score       CookiePoints
14 0
13 0
14 1
17 2
17 0
19 1
20 2
22 3
23 1
17 0
19 1
20 2
22 3
21 0

注意这是一个minimal, reproducible example .解决方案必须使用 Pandas DataFrame,并且最好只使用矢量化操作。

最佳答案

这当然是一个棘手的问题,但仍然可以在 Pandas 中解决。 (更新V3方案)

版本 3(OneLiner)

score = pd.Series([14,13,14,17,17,19,20,22,23,17,19,20,22,21])
result = score.diff().gt(0).pipe(lambda x:x.groupby((~x).cumsum()).cumsum().mod(3).replace(0,3).where(x,0).map(int))

版本 2

score = pd.Series([14,13,14,17,17,19,20,22,23,17,19,20,22,21])

mask= score.diff()>0

result = mask.groupby((~mask).cumsum()).cumsum().mod(3).replace(0,3).where(mask,0).map(int)

版本 1

score = pd.Series([14,13,14,17,17,19,20,22,23,17,19,20,22,21])

mask= score.diff()>0 # Identify score going up

mask

0 False
1 False
2 True
3 True
4 False
5 True
6 True
7 True
8 True
9 False
10 True
11 True
12 True
13 False
dtype: bool

# Use False Cumsum to group True values

group = (mask==False).cumsum()

group
0 1
1 2
2 2
3 2
4 3
5 3
6 3
7 3
8 3
9 4
10 4
11 4
12 4
13 5
dtype: int64

# Groupby False Cumsum
temp = mask.groupby(group).cumsum().map(int)
temp

0 0
1 0
2 1
3 2
4 0
5 1
6 2
7 3
8 4
9 0
10 1
11 2
12 3
13 0
dtype: int64

# Fix Cap at 3
# result = temp.where(temp<=3,temp.mod(3)) # This is Wrong.

result = temp.mod(3).replace(0,3).where(mask,0)
result

0 0
1 0
2 1
3 2
4 0
5 1
6 2
7 3
8 1
9 0
10 1
11 2
12 3
13 0
dtype: int64

关于python - Pandas :根据另一列增加或重置计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56914680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com