python - 用 Pandas 计算连胜纪录

标签 python pandas dataframe shift

我以为我知道该怎么做,但我正在努力解决这个问题。我正在尝试使用一个函数来创建一个新列。该函数查看当前行中 win 列的值,并需要将其与 win 列中的前一个数字进行比较,如下面的 if 语句所示。获胜列永远只会是 0 或 1。

import pandas as pd
data = pd.DataFrame({'win': [0, 0, 1, 1, 1, 0, 1]})
print (data)

   win
0    0
1    0
2    1
3    1
4    1
5    0
6    1

def streak(row):
    win_current_row = row['win']
    win_row_above = row['win'].shift(-1)
    streak_row_above = row['streak'].shift(-1)

    if (win_row_above == 0) & (win_current_row == 0):
        return 0
    elif (win_row_above == 0) & (win_current_row ==1):
        return 1
    elif (win_row_above ==1) & (win_current_row == 1):
        return streak_row_above + 1
    else:
        return 0

data['streak'] = data.apply(streak, axis=1)

所有这一切都以这个错误结束:

AttributeError: ("'numpy.int64' object has no attribute 'shift'", 'occurred at index 0')

在其他示例中,我看到引用 df['column'].shift(1) 的函数,所以我很困惑为什么我在这种情况下似乎无法做到这一点。

我也想得到的输出是:

result = pd.DataFrame({'win': [0, 0, 1, 1, 1, 0, 1], 'streak': ['NaN', 0 , 1, 2, 3, 0, 1]})
print(result)

   win streak
0    0    NaN
1    0      0 
2    1      1
3    1      2
4    1      3
5    0      0
6    1      1

感谢您帮助我摆脱困境。

最佳答案

使用 pandas 时一个相当常见的技巧是按连续值分组。这个技巧是well-described here .

要解决您的特定问题,我们要groupby 连续值,然后使用cumsum,这意味着损失组(组0) 的累积总和为 0,而获胜组(或 1 组)将跟踪连胜记录。

grouper = (df.win != df.win.shift()).cumsum()
df['streak'] = df.groupby(grouper).cumsum()

   win  streak
0    0       0
1    0       0
2    1       1
3    1       2
4    1       3
5    0       0
6    1       1

为了便于解释,这是我们的 grouper Series,它允许我们按 10的:

print(grouper)

0    1
1    1
2    2
3    2
4    2
5    3
6    4
Name: win, dtype: int64

关于python - 用 Pandas 计算连胜纪录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52976336/

相关文章:

python - 优化 Django QuerySet 序列

python - 使用最新的 Pandas API 计算指数移动平均线

python - 为什么 Pandas 和 Seaborn 对相同的数据生成不同的 KDE 图?

python - pandas.core.groupby.DataFrameGroupBy.idxmin() 非常慢,如何使我的代码更快?

类切片中的 Python 列表不起作用

python - 树莓派无法安装Nmap,依赖失败

python - 如何从数据框字典创建 Pandas DataFrame?

python - 填充空行

python - 将 float 转换为 int 时,尾随数字从何而来?

r - 如何选择 R 数据框中满足特定条件的第一行?