如何查找列中元素的进一步出现

问题描述 投票:0回答:1

我有一个具有6000行和一列的数据框。我必须在第二列中找到相同的元素,但要使它们之间的距离最大。带有列表的示例为:

list = [2,1,3,1,2,4,5,1,3,2,1,5]

我希望输出是一对:

(list[1], list[10])

有什么想法吗?谢谢你们!

python python-3.x pandas dataframe find-occurrences
1个回答
0
投票

您可以尝试这个。使用pd.grouby索引并索引第一个元素和最后一个元素。

pd.grouby

或者您可以使用lst = [2,1,3,1,2,4,5,1,3,2,1,5] df = pd.DataFrame(lst,columns=['vals'] df.reset_index().groupby('vals').agg(['first','last']) index first last vals 1 1 10 2 0 9 3 2 8 4 5 5 5 6 11 进行命名聚合。

pd.NamedAgg

如果您希望它们与元组在同一列中,请使用pd.NamedAgg

df.reset_index().groupby('vals').agg(
                     first_occurrence=pd.NamedAgg(column='index',aggfunc='first'),
                     last_occurrence=pd.NamedAgg(column='index',aggfunc='last')
                     )

      first_occurrence  last_occurrence
vals
1                   1              10
2                   0               9
3                   2               8
4                   5               5
5                   6              11
© www.soinside.com 2019 - 2024. All rights reserved.