Having identified outliers, let's review two common treatments:
- Exclusion: A straightforward method where outliers are simply removed. This is akin to discarding burnt pieces in a batch of cookies to maintain the overall quality.
- Transformation: This method involves changing the data to reduce skewness, similarly to applying a filter to a photo to bring all objects to a common exposure level.
For a hands-on approach, let's exclude outliers from our dataset:
# Excluding outliers based on the Z-score method
df_excluded = df[(df['MedInc_zscore'] <= 3) & (df['MedInc_zscore'] >= -3)]
print("Data after excluding outliers:", df_excluded.shape[0], "instances")
Data after excluding outliers: 20295 instances
Another approach is applying a transformation, such as taking the logarithm to reduce the impact of extreme values, demonstrated with Python code:
import numpy as np
# Log transformation
df['MedInc_log'] = np.log(df['MedInc'] + 1) # We use +1 to avoid taking the logarithm of zero
# Viewing the distribution after transformation
print("Data after log transformation:\n", df['MedInc_log'].describe())
Data after log transformation:
count 20640.000000
mean 1.516995
std 0.358677
min 0.405398
25% 1.270715
50% 1.511781
75% 1.748025
max 2.772595
Name: MedInc_log, dtype: float64
The log transformation of the MedInc column helps normalize data, particularly useful for right-skewed distributions. By applying the natural logarithm (adding one to handle zeros), we adjust data scales, compressing the higher values more than the lower ones and minimizing the outliers' impact. This shift towards a more normal distribution can improve data robustness and the reliability of predictive models by reducing sensitivity to extreme values.