python - Pandas :删除连续重复

标签 python pandas

在 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/

相关文章:

python - 尝试使用 requests 将 php curl 脚本转换为 python

python - 如何让Python将函数识别为生成器函数?

python - 减去相同的两个日期时如何计算为 1 天

python - 将 DataFrame 或一系列列表转换为一个堆叠的 DataFrame(或系列)

python - WebdriverWait 显示 TimeoutException,如果我使用 sleep.time 它工作正常

python - 使用 Python 取消汇总数据集

python - 计算 pandas 列中条目的频率,然后使用 X 轴字符串标签将它们绘制成图

python - 如何将巨大的 Pandas 数据框保存到 hdfs?

python - 如何获取 Pandas DataFrame 中 2 个列表的差异?

python - 如何缩放直方图 Pandas 图的 y 轴?