NumPy/Pandas:删除顺序重复值(相当于没有排序的bash uniq)

DrA*_*rAl 3 python numpy pandas

给出像这样的Pandas系列(或numpy数组):

import pandas as pd
myseries = pd.Series([1, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 2, 2, 3, 3, 1])
Run Code Online (Sandbox Code Playgroud)

有没有一种很好的方法来删除顺序重复,就像unix uniq工具一样?numpy/pandas unique()和pandas drop_duplicates函数删除所有重复项(如unix的| sort | uniq),但我不想这样:

>>> print(myseries.unique())
[1 2 3 4]
Run Code Online (Sandbox Code Playgroud)

我要这个:

>>> print(myseries.my_mystery_function())
[1, 2, 3, 4, 3, 2, 3, 1]
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 6

比较by ne(!=)与shifted Series和filter by boolean indexing:

myseries = myseries[myseries.ne(myseries.shift())].tolist()
print (myseries)
[1, 2, 3, 4, 3, 2, 3, 1]
Run Code Online (Sandbox Code Playgroud)

如果性能很重要,请使用Divakar解决方案.