删除重复项的行为不符合预期

2024-04-20 07:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas系列,其索引包含几个重复项,我使用drop_duplicates使其索引可用于对其他系列/数据帧的进一步切片:

In[1]: test
Out[1]: 
5575    21010210
5575    21010210
5577    21010210
5577    21010210
5577    21010210
5583    21010210
5583    21010210
5583    21010210
5586    21010210
5586    21010210
5586    21010210
8545    21010210
8545    21010210
8718    21000102
8718    21000102
8721    21000102
8721    21000102
Name: CC, dtype: object

当我应用test.drop_duplicates()时,我希望所有现有的索引都保持不变,尽管没有重复。出于某种原因,pandas没有将其中一些索引识别为重复索引,只是将它们从数据帧中清除:

In[2]: test.drop_duplicates()
Out[2]: 
5575    21010210
8718    21000102
Name: CC, dtype: object

奇怪的是,如果我之前重置了索引,drop_duplicates方法将正常工作:

In[3]: test.reset_index().drop_duplicates()
Out[3]: 
    index        CC
0    5575  21010210
2    5577  21010210
5    5583  21010210
8    5586  21010210
11   8545  21010210
13   8718  21000102
15   8721  21000102

为什么熊猫会从操作中删除一些指数?如何在不重置索引的情况下有效地删除这些重复项?你知道吗


Tags: 数据方法nameintestpandasindexobject
1条回答
网友
1楼 · 发布于 2024-04-20 07:24:30

这是你的熊猫对象:

import pandas as pd

data = [
    21010210, 21010210, 21010210, 21010210, 21010210, 21010210, 
    21010210, 21010210,  21010210, 21010210, 21010210, 21010210, 
    21010210, 21000102, 21000102, 21000102, 21000102
]

idx = [
    5575, 5575, 5577, 5577, 5577, 5583, 5583, 5583, 
    5586, 5586, 5586, 8545, 8545, 8718, 8718, 8721, 8721
]

series = pd.Series(data, index=idx).rename("CC")

print(series)

>>>
5575    21010210
5575    21010210
5577    21010210
5577    21010210
5577    21010210
5583    21010210
5583    21010210
5583    21010210
5586    21010210
5586    21010210
5586    21010210
8545    21010210
8545    21010210
8718    21000102
8718    21000102
8721    21000102
8721    21000102
Name: CC, dtype: int64

现在,如果运行^{},将忽略索引:

Return DataFrame with duplicate rows removed, optionally only considering certain columns. Indexes, including time indexes are ignored

print(series.drop_duplicates())

5575    21010210
8718    21000102
Name: CC, dtype: int64

最后,^{}将返回一个dataframe,其中前一个索引插入到数据帧列中,索引将重置:

print(series.reset_index())
    index        CC
0    5575  21010210
1    5575  21010210
2    5577  21010210
3    5577  21010210
4    5577  21010210
5    5583  21010210
6    5583  21010210
7    5583  21010210
8    5586  21010210
9    5586  21010210
10   5586  21010210
11   8545  21010210
12   8545  21010210
13   8718  21000102
14   8718  21000102
15   8721  21000102
16   8721  21000102

Reset the index of the DataFrame, and use the default one instead.

这意味着drop_duplicates()现在将同时考虑这两个列。你知道吗

print(series.reset_index().drop_duplicates())
    index        CC
0    5575  21010210
2    5577  21010210
5    5583  21010210
8    5586  21010210
11   8545  21010210
13   8718  21000102
15   8721  21000102

最有效的方法是

print(series.loc[~series.index.duplicated()])
5575    21010210
5577    21010210
5583    21010210
5586    21010210
8545    21010210
8718    21000102
8721    21000102
Name: CC, dtype: int64

相关问题 更多 >