Pandas 系列中的 keep 引數在 drop_duplicates() 方法中是如何工作的?
Pandas 系列建構函式中的 drop_duplicate() 方法用於從系列物件中刪除重複值。此方法清理重複值並返回一個包含修改行的新系列,並且不會更改原始系列物件。相反,它將返回一個新的系列物件。
drop_duplicates() 方法中的一個重要引數是“Keep”,此引數的預設值為“first”,它保留第一次出現的數值並刪除其餘的。我們還可以為 keep 引數指定 Last 和 False 值。
如果 keep=False,它將刪除所有重複值。或者如果 keep=“Last”,它將刪除重複值,除了最後一次出現的值。
示例 1
在下面的示例中,我們首先使用 Pandas 系列方法和字串列表建立了一個 Pandas 系列。稍後,我們透過設定 keep=“last”應用了 drop_duplicates() 方法。
# import pandas package import pandas as pd # create pandas series with duplicate values series = pd.Series(['Robin', 'John', 'Nori', 'Yi', 'Robin', 'Amal', 'Nori']) print(series) # delete duplicate values with keep='last' result = series.drop_duplicates(keep='last') print('Output:
',result)
輸出
輸出如下所示:
0 Robin 1 John 2 Nori 3 Yi 4 Robin 5 Amal 6 Nori dtype: object Output: 1 John 3 Yi 4 Robin 5 Amal 6 Nori dtype: object
值“Robin”在索引位置“0”和“4”處重複,值“Nori”也在索引位置“2”和“6”處重複。
透過設定 keep=Last,我們已成功刪除了索引位置 0 和 2 處的值。
示例 2
對於相同的示例,我們將 keep 引數的值從“last”更改為“first”。
# import pandas package import pandas as pd # create pandas series with duplicate values series = pd.Series(['Robin', 'John', 'Nori', 'Yi', 'Robin', 'Amal', 'Nori']) print(series) # delete duplicate values with keep='first' result = series.drop_duplicates(keep='first') print('Output:
',result)
輸出
您將獲得以下輸出:
0 Robin 1 John 2 Nori 3 Yi 4 Robin 5 Amal 6 Nori dtype: object Output: 0 Robin 1 John 2 Nori 3 Yi 5 Amal dtype: object
對於上述輸出,索引位置“4”和“6”處的重複值被刪除,因為值“Robin”和“Nori”在索引位置“0”和“2”處首次出現。
示例 3
在此示例中,我們將看到 drop_duplicates() 方法對於 keep=False 值是如何工作的。我們首先使用整數列表建立了一個系列物件,然後應用了該方法。
# import pandas package import pandas as pd # create pandas series with duplicate values series = pd.Series([1,2,1,3,4,2,6,4,5]) print(series) # delete duplicate values with keep=False result = series.drop_duplicates(keep=False) print('Output:
',result)
輸出
輸出如下所示:
0 1 1 2 2 1 3 3 4 4 5 2 6 6 7 4 8 5 dtype: int64 Output: 3 3 6 6 8 5 dtype: int64
來自 drop_duplicates() 方法的結果系列物件只有 3 行,而原始系列有 9 行。發生這種情況是因為 keep=False 將刪除所有重複值,它不保留任何單個出現的值。
廣告