Python Pandas - 返回已刪除重複值的索引,同時保留最後一次出現
要返回已刪除重複值的索引,同時保留最後一次出現,請使用index.drop_duplicates() 方法。使用具有值last 的keep 引數。
首先,匯入所需的庫 -
import pandas as pd
使用一些重複建立索引
index = pd.Index(['Car','Bike','Airplane','Ship','Airplane'])
顯示索引 -
print("Pandas Index with duplicates...\n",index)返回已刪除重複值的索引。“keep”引數值“last”為每組重複條目保留最後一次出現 -
print("\nIndex with duplicate values removed (keeping the last occurrence)...\n",index.drop_duplicates(keep='last'))
示例
以下是程式碼 -
import pandas as pd
# Creating the index with some duplicates
index = pd.Index(['Car','Bike','Airplane','Ship','Airplane'])
# Display the index
print("Pandas Index with duplicates...\n",index)
# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)
# get the bytes in the data
print("\nGet the bytes...\n",index.nbytes)
# get the dimensions of the data
print("\nGet the dimensions...\n",index.ndim)
# Return Index with duplicate values removed
# The "keep" parameter with value "last" keeps the last occurrence for each set of duplicated entries
print("\nIndex with duplicate values removed (keeping the last occurrence)...\n",index.drop_duplicates(keep='last'))輸出
這將生成以下程式碼 -
Pandas Index with duplicates... Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'], dtype='object') The dtype object... object Get the bytes... 40 Get the dimensions... 1 Index with duplicate values removed (keeping the last occurrence)... Index(['Car', 'Bike', 'Ship', 'Airplane'], dtype='object')
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP