我正在寻找一种有效的函数来查找至少连续出现三次且不间断的标记。
输入示例:
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/