chintan s
chintan s

Reputation: 6488

Python remove outliers from data

I have a data frame as following:

ID Value
A   70
A   80
B   75
C   10
B   50
A   1000
C   60
B   2000
..  ..

I would like to group this data by ID, remove the outliers from the grouped data (the ones we see from the boxplot) and then calculate mean.

So far

grouped = df.groupby('ID')

statBefore = pd.DataFrame({'mean': grouped['Value'].mean(), 'median': grouped['Value'].median(), 'std' : grouped['Value'].std()})

How can I find outliers, remove them and get the statistics.

Upvotes: 4

Views: 17854

Answers (3)

Yogesh Kawadkar
Yogesh Kawadkar

Reputation: 11

Q1 = df['Value'].quantile(0.25)
Q3 = df['Value'].quantile(0.75)
IQR = Q3 - Q1

data = df[~((df['Value'] < (Q1 - 1.5 * IQR)) |(df['Value'] > (Q3 + 1.5 * 
IQR))).any(axis=1)]

Upvotes: 1

Sam
Sam

Reputation: 4090

I believe the method you're referring to is to remove values > 1.5 * the interquartile range away from the median. So first, calculate your initial statistics:

statBefore = pd.DataFrame({'q1': grouped['Value'].quantile(.25), \
'median': grouped['Value'].median(), 'q3' : grouped['Value'].quantile(.75)})

And then determine whether values in the original DF are outliers:

def is_outlier(row):
    iq_range = statBefore.loc[row.ID]['q3'] - statBefore.loc[row.ID]['q1']
    median = statBefore.loc[row.ID]['median']
    if row.Value > (median + (1.5* iq_range)) or row.Value < (median - (1.5* iq_range)):
        return True
    else:
        return False
#apply the function to the original df:
df.loc[:, 'outlier'] = df.apply(is_outlier, axis = 1)
#filter to only non-outliers:
df_no_outliers = df[~(df.outlier)]

Upvotes: 11

B. M.
B. M.

Reputation: 18628

just do :

In [187]: df[df<100].groupby('ID').agg(['mean','median','std'])
Out[187]: 
   Value                  
    mean median        std
ID                        
A   75.0   75.0   7.071068
B   62.5   62.5  17.677670
C   35.0   35.0  35.355339

Upvotes: 0

Related Questions