在 pandas 中只删除连续重复项的最有效方法是什么?
drop_duplicates 给出了这个:
In [3]: a = pandas.Series([1,2,2,3,2], index=[1,2,3,4,5])
In [4]: a.drop_duplicates()
Out[4]:
1 1
2 2
4 3
dtype: int64
但我想要这个:
In [4]: a.something()
Out[4]:
1 1
2 2
4 3
5 2
dtype: int64
最佳答案
使用 shift
:
a.loc[a.shift(-1) != a]
Out[3]:
1 1
3 2
4 3
5 2
dtype: int64
所以上面使用 bool 标准,我们将数据帧与移动了 -1 行的数据帧进行比较以创建掩码
另一种方法是使用diff
:
In [82]:
a.loc[a.diff() != 0]
Out[82]:
1 1
2 2
4 3
5 2
dtype: int64
但是如果你有大量的行,这会比原来的方法慢。
更新
感谢 Bjarke Ebert 指出一个细微的错误,我实际上应该使用 shift(1)
或仅使用 shift()
因为默认的句点是 1,这将返回第一个连续值:
In [87]:
a.loc[a.shift() != a]
Out[87]:
1 1
2 2
4 3
5 2
dtype: int64
注意索引值的差异,感谢@BjarkeEbert!
关于python - Pandas :删除连续重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19463985/