如何在 Python 中识别和检索 Pandas DataFrame 中的重复项?

Patricia Arquette
发布: 2024-10-25 11:31:02
原创
826 人浏览过

How to Identify and Retrieve Duplicate Items within a Pandas DataFrame in Python?

如何在 Python 中使用 Pandas 获取所有重复项的列表

在处理数据集时,经常会遇到重复的条目。在这种情况下,您希望使用 Pandas 识别数据集中的所有重复项。

要实现此目的,您可以使用以下方法:

方法 1(使用以下命令打印所有行)重复 ID):

<code class="python">import pandas as pd

# Read the CSV data into a DataFrame
df = pd.read_csv("dup.csv")

# Extract the "ID" column
ids = df["ID"]

# Create a new DataFrame with only the duplicate values
duplicates = df[ids.isin(ids[ids.duplicated()])]

# Sort the DataFrame by the "ID" column
duplicates.sort_values("ID", inplace=True)

# Print the duplicate values
print(duplicates)</code>
登录后复制

方法 2(分组并连接重复组):

此方法组合重复组,从而得到简洁的表示重复项目的数量:

<code class="python"># Group the DataFrame by the "ID" column
grouped = df.groupby("ID")

# Filter the grouped DataFrame to include only groups with more than one row
duplicates = [g for _, g in grouped if len(g) > 1]

# Concatenate the duplicate groups into a new DataFrame
duplicates = pd.concat(duplicates)

# Print the duplicate values
print(duplicates)</code>
登录后复制

使用方法 1 或方法 2,您可以成功获取数据集中所有重复项目的列表,以便您直观地检查它们并调查差异。

以上是如何在 Python 中识别和检索 Pandas DataFrame 中的重复项?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!