📅  最后修改于: 2023-12-03 15:12:03.117000             🧑  作者: Mango
在数据处理中,计算数据集中有多少个重复的行或列是很常见的需求,使用 Pandas 可以很方便地实现。
下面介绍几种方法,可以计算重复的行或列。
使用 Pandas 中的 duplicated()
方法,可以返回一个布尔数组,标记每行是否为重复行。通过 sum()
方法,即可计算重复行的数量。
import pandas as pd
df = pd.read_csv('data.csv')
n_duplicates = df.duplicated().sum()
print("There are", n_duplicates, "duplicate rows in the dataset.")
输出结果:
There are 20 duplicate rows in the dataset.
如果想要按列检查重复,可以使用 Pandas 中的 duplicated()
方法,在传入 subset
参数指定需要检查的列。
例如,下面的代码将只检查 'name' 和 'age' 两列是否重复:
import pandas as pd
df = pd.read_csv('data.csv')
n_duplicates = df.duplicated(subset=['name', 'age']).sum()
print("There are", n_duplicates, "duplicate rows based on 'name' and 'age'.")
输出结果:
There are 13 duplicate rows based on 'name' and 'age'.
如果想要删除重复的行,可以使用 Pandas 中的 drop_duplicates()
方法。该方法会返回一个去重后的新 DataFrame,具有以下参数:
subset
:指定需要检查的列,默认为所有列。keep
:保留哪一个重复的行。可选值为 'first'
、'last'
或 False
。例如,下面的代码将会删除所有重复的行:
import pandas as pd
df = pd.read_csv('data.csv')
df = df.drop_duplicates()
print("After dropping duplicates, the dataframe has", len(df), "rows.")
输出结果:
After dropping duplicates, the dataframe has 80 rows.
如果想要将重复的行合并为一个唯一的行,可以使用 Pandas 中的 groupby()
方法。该方法可以将 DataFrame 按照指定的列分组,并对每组进行聚合。
下面的代码将按照 'name'、'age' 分组,并对每个组进行求和:
import pandas as pd
df = pd.read_csv('data.csv')
df_grouped = df.groupby(['name', 'age']).sum()
print(df_grouped)
输出结果:
weight height
name age
Bob 25.0 90 170
40.0 70 160
50.0 80 175
John 30.0 85 175
45.0 75 165
Tom 25.0 70 165
35.0 60 160
上述代码将 'weight' 和 'height' 列按照 'name' 和 'age' 分组,并对每个组进行求和。
如果 DataFrame 很大,使用 duplicated()
方法检查重复行可能会耗费大量内存。此时可以使用 numpy 中的 unique()
方法和 return_counts=True
参数来计算重复行的数量,如下所示:
import pandas as pd
import numpy as np
df = pd.read_csv('data.csv')
# 将 DataFrame 转为 numpy 数组,并进行 hash 计算
hashed = np.ravel(pd.util.hash_pandas_object(df, index=True))
# 统计出现次数大于1的 hash 所对应的行数
_, counts = np.unique(hashed, return_counts=True)
n_duplicates = np.sum(counts[counts > 1])
print("There are", n_duplicates, "duplicate rows in the dataset.")
输出结果与第一种方法相同。此方法不仅仅适用于计算重复行,也可以用来计算其他的值。