You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python异常值处理函数修改求助:返回去异常值的完整DataFrame

Fixing Your Outlier Function to Return the Full Cleaned DataFrame

Got it, let's tweak your function so it returns the full cleaned DataFrame instead of just the processed single column. The core issue with your original code is that it only receives a single Series (the target column) instead of the entire dataset—so it can't preserve the rest of your data. Here's how to adjust it:

Modified Function Code

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

def remove_outliers_and_plot(df, target_col):
    '''Funktion um die Zahl der mathematisch definierten Ausreißer zu analysieren. 
    Zeigt die Verteilung mit und ohne Ausreißer an und gibt den bereinigten DataFrame zurück.'''
    # Extract the target column as a Series
    variable = df[target_col]
    
    # Calculate quartiles and IQR
    q1, q3 = variable.quantile(0.25), variable.quantile(0.75)
    iqr = q3 - q1
    
    # Define outlier fences
    l_fence, u_fence = q1 - 1.5*iqr , q3 + 1.5*iqr
    
    # Identify outliers
    outliers = variable[(variable < l_fence) | (variable > u_fence)]
    print('Total Outliers of', target_col,':', outliers.count())
    
    # Filter the entire DataFrame (not just the single column)
    filtered_df = df.drop(outliers.index, axis=0)
    
    # Create boxplots for original and cleaned target column
    out_variables = [variable, filtered_df[target_col]]
    out_titles = [' Verteilung mit Ausreißer', ' Verteilung ohne Ausreißer']
    title_size = 10
    font_size = 8
    
    plt.figure(figsize=(20, 5))
    for ax, outlier_series, title in zip(range(1,3), out_variables, out_titles):
        plt.subplot(2, 1, ax)
        plt.subplots_adjust(bottom=0.2, right=0.8, top=0.9, hspace=.5)
        sns.boxplot(outlier_series).set_title(f'{target_col}{title}', fontsize=title_size)
        plt.xticks(fontsize=font_size)
        plt.xlabel(target_col, fontsize=font_size)
    
    # Return the full cleaned DataFrame
    return filtered_df

How to Use the Modified Function

# Assuming "daten" is your original DataFrame
cleaned_data = remove_outliers_and_plot(df=daten, target_col="Alter")

# Now cleaned_data contains all columns from your original dataset, minus rows with outliers in the "Alter" column

Key Changes Explained

  • Parameter Update: The function now takes the full DataFrame (df) and the name of your target column (target_col) instead of just a single Series. This lets us access and preserve all your data.
  • Removed Global Variable: We replaced the global filtered with a local filtered_df to avoid unintended side effects from global variables, and to store the complete cleaned dataset.
  • Return Value: Added return filtered_df so you can capture the full cleaned DataFrame after running the function.
  • Preserved Plotting Logic: The boxplots still focus on the target column, so you get the same visualization while gaining access to the full dataset.

内容的提问来源于stack exchange,提问作者ml_learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:12:45