如何在 Pandas 系列中刪除具有重複索引的行?


透過在 pandas 系列建構函式中使用 duplicated() 方法,我們可以輕鬆識別系列物件索引中的重複值。duplicated() 方法用於識別系列物件中的重複值。

duplicated() 方法將返回一個包含布林值的系列。布林值 False 表示單個出現的值,即唯一值。重複值用布林值 True 表示。

示例 1

在這裡,我們將看到如何刪除具有重複索引的系列物件的行。

# importing pandas package
import pandas as pd

#create series
series = pd.Series(["a", "b", "c", "d", "e"],index=[1, 2, 1, 3, 2])

print(series)

# getting the index data
index = series.index

# removing duplicate indices separately
result = series[~index.duplicated(keep="first")]

print(result)

解釋

最初,我們使用 pandas.Series() 函式建立了一個 pandas 系列物件,其索引標籤為 [1, 2,1, 3, 2]。然後,我們對索引資料應用 duplicated() 方法以識別重複標籤。

之後,我們應用“~”反轉結果布林值,並將此資料傳送到原始系列作為子集,以獲取一個沒有任何重複索引的新系列物件。

輸出

輸出如下所示:

1    a
2    b
1    c
3    d
2    e
dtype: object

1    a
2    b
3    d
dtype: object

在上面的輸出塊中,我們可以看到原始系列物件以及沒有重複標籤的結果系列物件。

示例 2

讓我們再舉一個例子,刪除具有重複索引的系列物件的行。

# importing package
import pandas as pd
import numpy as np

# creating pandas series
series = pd.Series(np.random.randint(1,100,10),
   index=["a", "b", "a", "d", "c", "e", "f", "c", "d", "e"])

print(series)

# getting the index data
index = series.index

# removing duplicate indices separately
result = series[~index.duplicated(keep="first")]

print(result)

解釋

最初,我們建立了帶有標記索引資料的系列物件,然後應用 duplicated() 方法來識別重複標籤。

輸出

輸出如下所示:

a    66
b    73
a    83
d    63
c    23
e    56
f    55
c    22
d    26
e    20
dtype: int32

a    66
b    73
d    63
c    23
e    56
f    55
dtype: int32

標籤 a、d、c、e 在初始系列物件中出現不止一次,並且這些行在結果系列物件中被刪除。

更新於: 2022-03-07

2K+ 閱讀量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告