在熊猫中仅丢弃连续重复项的最有效方法是什么?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 12 24 3dtype: int64但是我想要这个:In [4]: a.something()Out[4]: 1 12 24 35 2dtype: int64
3 回答
慕桂英4014372
TA贡献1871条经验 获得超13个赞
用途shift:
a.loc[a.shift(-1) != a]
Out[3]:
1 1
3 2
4 3
5 2
dtype: int64
因此,以上使用布尔标准,我们将数据框与移动了-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!
长风秋雁
TA贡献1757条经验 获得超7个赞
这是一个更新,它将使其与多个列一起使用。使用“ .any(axis = 1)”组合各列的结果:
cols = ["col1","col2","col3"]
de_dup = a[cols].loc[(a[cols].shift() != a[cols]).any(axis=1)]
添加回答
举报
0/150
提交
取消