Python重复数据处理、空值处理、异常值处理

Python重复数据处理、空值处理、异常值处理分别用哪些代码

在处理重复数据、空值和异常值时,可以使用以下代码:

  1. 重复数据处理:
# 检查重复行
df.duplicated()

# 删除重复行
df.drop_duplicates()
  1. 空值处理:
# 检查是否存在空值
df.isnull()

# 删除包含空值的行或列
df.dropna()

# 填充空值
df.fillna(value)
  1. 异常值处理:
# 定义异常值的阈值范围
lower_threshold = 0
upper_threshold = 100

# 根据阈值删除异常值
df = df[(df['column'] >= lower_threshold) & (df['column'] <= upper_threshold)]

# 使用中位数替换异常值
median = df['column'].median()
df['column'] = np.where(df['column'] < lower_threshold, median, df['column'])
df['column'] = np.where(df['column'] > upper_threshold, median, df['column'])

# 使用平均值替换异常值
mean = df['column'].mean()
df['column'] = np.where(df['column'] < lower_threshold, mean, df['column'])
df['column'] = np.where(df['column'] > upper_threshold, mean, df['column'])

请根据您的具体需求和数据集选择适当的方法进行重复数据、空值和异常值的处理。确保在使用这些代码之前先导入必要的库(例如,pandas、numpy)。

1.重复数据处理

删除重复行:df.drop_duplicates(inplace=True)

标记重复行:df['is_duplicate'] = df.duplicated()

删除指定列的重复行:df.drop_duplicates(subset=['column_name'], inplace=True)

2.空值处理

删除包含空值的行:df.dropna(inplace=True)

填充空值:df.fillna(value, inplace=True)

3.异常值处理

删除包含异常值的行:df = df[(df['column_name'] >= lower_bound) & (df['column_name'] <= upper_bound)]

替换异常值:df.loc[df['column_name'] < lower_bound, 'column_name'] = replacement_value
df.loc[df['column_name'] > upper_bound, 'column_name'] = replacement_value