Python Pandas - 返回删除重复值并保留最后一次出现的索引
pythonpandasserver side programmingprogramming更新于 2025/12/31 7:08:17
要返回删除重复值并保留最后一次出现的索引,请使用 index.drop_duplicates() 方法。使用 keep 参数,值为 last。
首先,导入所需的库 −
import pandas as pd
创建带有一些重复项的索引−
index = pd.Index(['Car','Bike','Airplane','Ship','Airplane'])
显示索引 −
print("Pandas Index with duplicates...\n",index)
返回删除了重复值的 Index。值为 "last" 的 "keep" 参数保留每组重复条目的最后一次出现 −
print("\n删除重复值的索引(保留最后一次出现的值)...\n",index.drop_duplicates(keep='last'))
示例
以下是代码 −
import pandas as pd
# 创建包含一些重复项的索引
index = pd.Index(['Car','Bike','Airplane','Ship','Airplane'])
# 显示索引
print("Pandas Index with duplicates...\n",index)
# 返回数据的 dtype
print("\ndtype 对象...\n",index.dtype)
# 获取数据中的字节
print("\nGet the bytes...\n",index.nbytes)
# 获取数据的维度
print("\nGet the Dimensions...\n",index.ndim)
# 返回删除了重复值的索引
# 值为 "last" 的 "keep" 参数保留每组重复条目的最后一次出现
print("\n删除重复值的索引(保留最后一次出现的值)...\n",index.drop_duplicates(keep='last'))
输出
这将产生以下代码 −
Pandas Index with duplicates... Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'], dtype='object') dtype 对象... object Get the bytes... 40 Get the dimensions... 1 删除重复值的索引(保留最后一次出现的值)... Index(['Car', 'Bike', 'Ship', 'Airplane'], dtype='object')
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

