python - 检测三次相等元素列表的有效函数

标签 python python-3.x pandas list loops

我正在寻找一种有效的函数来查找至少连续出现三次且不间断的标记。

输入示例:

import pandas as pd
marks = [83, 79, 83, 83, 83, 79, 79, 83]
student_id = [101, 102, 103, 104, 105, 106, 107, 108]
d = {'student_id':student_id,'marks':marks}
df = pd.DataFrame (d)

期望的输出:

83

如果可能的话,我正在寻找比使用跟踪前 2 个标记的 for 循环逐行循环更有效的方法。也就是说,我正在寻找比以下更好的东西:

def thrice_f (marks, number_of_apperances):
    cache = marks[0]
    counter = 1
    for mark in marks[1:]:
        if mark == cache:
            counter += 1
            if counter == number_of_apperances:
                return cache
        else:
            counter = 1
        cache = mark

最佳答案

您可以使用 diff + ne + cumsum 来识别连续标记组。然后索引恰好连续出现 3 次的标记:

groups = df['marks'].diff().ne(0).cumsum()
out = df.loc[groups.isin(groups.value_counts().eq(3).pipe(lambda x: x[x].index)), 'marks'].unique()

输出:

[83]

关于python - 检测三次相等元素列表的有效函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71861639/

相关文章:

python - bat 脚本链接到 python 脚本

python - 将列表中的每个元素乘以 2

python-3.x - 如何仅从 csv 文件(Pandas)加载列名?

python - 如何在 Pandas 中读取带有分号分隔符的文件

python - 使用多个 If-else 创建 Pandas 变量

python - 用Python中另一个列表中的项目替换满足某些条件的列表元素

python - Pandas 在第一个 % 符号和第二个字母上拆分列

python - 如何在 Django 中的每个管理页面加载上运行 python 函数

python - 在Python中查找两个字典列表之间的差异

python - Pandas 计算连续行之间存在 X 秒差异的次数