Replace outliers with mean python
I have a python data-frame in which there are some outlier values. I would like to replace them with the median values of the data, had those values not been there. Show
So, I want to replace all the values > 75 with the median value of the dataset of the remaining dataset, i.e., the median value of I'm trying to do the following:
But somehow, the below code not working IntroductionThe difference between a good and an average machine learning model is often its ability to clean data. One of the biggest challenges in data cleaning is the identification and treatment of outliers. In simple terms, outliers are observations that are significantly different from other data points. Even the best machine learning algorithms will underperform if outliers are not cleaned from the data because outliers can adversely affect the training process of a machine learning algorithm, resulting in a loss of accuracy. In this guide, you will learn about techniques for outlier identification and treatment in Python. DataIn this guide, we will be using a fictitious dataset of loan applications containing 600 observations and 6 variables: 1. Income - Annual income of the applicant (in US dollars) 2. Loan_amount - Loan amount (in US dollars) for which the application was submitted 3. Term_months - Tenure of the loan (in months) 4. Credit_score - Whether the applicant's credit score was good ("1") or not ("0") 5. Age - The applicant’s age in years 6. Approval_status - Whether the loan application was approved ("1") or not ("0") Let's start by loading the required libraries and the data.
python
The above output shows that there are 600 observations of 6 variables. All the variables have 600 records, indicating that there is no missing value in the data. Outlier IdentificationThere can be many reasons for the presence of outliers in the data. Sometimes the outliers may be genuine, while in other cases, they could exist because of data entry errors. It is important to understand the reasons for the outliers before cleaning them. We will start the process of finding outliers by running the summary statistics on the variables. This is done using the describe() function below, which provides a statistical summary of all the quantitative variables.
Looking at the 'Age' variable, it is easy to detect outliers resulting from incorrect data. The minimum and maximum ages are 0, and 200, respectively. These are incorrect, and we will treat them later in the guide. These outliers were easy to detect, butthat will not always be the case. In other cases, mathematical and visualization techniques must be used. These techniques are discussed in the following sections. Identifying Outliers with Interquartile Range (IQR)The interquartile range (IQR) is a measure of statistical dispersion and is calculated as the difference between the 75th and 25th percentiles. It is represented by the formula IQR = Q3 − Q1. The lines of code below calculate and print the interquartile range for each of the variables in the dataset.
python
The above output prints the IQR scores, which can be used to detect outliers. The code below generates an output with the 'True' and 'False' values. Points where the values are 'True' represent the presence of the outlier.
python
Identifying Outliers with SkewnessSeveral machine learning algorithms make the assumption that the data follow a normal (or Gaussian) distribution. This is easy to check with the skewness value, which explains the extent to which the data is normally distributed. Ideally, the skewness value should be between -1 and +1, and any major deviation from this range indicates the presence of extreme values. The first line of code below prints the skewness value for the 'Income' variable, while the second line prints the summary statistics.
python
The skewness value of 6.5 shows that the variable 'Income' has a right-skewed distribution, indicating the presence of extreme higher values. The maximum 'Income' value of USD 108,000 proves this point. Identifying Outliers with VisualizationIn the previous section, we used quantitative methods for outlier identification. This can also be achieved with visualization. Some of the common plots used for outlier detection are discussed below. 1. Box PlotThe box plot is a standardized way of displaying the distribution of data based on the five-number summary (minimum, first quartile (Q1), median, third quartile (Q3), and maximum). It is often used to identify data distribution and detect outliers. The line of code below plots the box plot of the numeric variable 'Loan_amount'.
python In the above output, the circles indicate the outliers, and there are many. It is also possible to identify outliers using more than one variable. We can modify the above code to visualize outliers in the 'Loan_amount' variable by the approval status.
python The output shows that the number of outliers is higher for approved loan applicants (denoted by the label '1') than for rejected applicants (denoted by the label '0'). 2. HistogramA histogram is used to visualize the distribution of a numerical variable. An outlier will appear outside the overall pattern of distribution. The line of code below plots a histogram of the 'Income' variable, using the hist() function. The above chart shows that the distribution is right-skewed, and there are extreme higher values at the right of the histogram. This step can be repeated for other variables as well. 3. ScatterplotA scatterplot visualizes the relationship between two quantitative variables. The data are displayed as a collection of points, and any points that fall outside the general clustering of the two variables may indicate outliers. The lines of code below generate a scatterplot between the variables 'Income' and 'Loan_amount'.
python The above chart indicates that most of the data points are clustered in the lower half of the plot. The points located to the extreme right of the x-axis or the y-axis indicate outliers. Outlier TreatmentIn the previous sections, we learned about techniques for outlier detection. However, this is only half of the task. Once we have identified the outliers, we need to treat them. There are several techniques for this, and we will discuss the most widely used ones below. Quantile-based Flooring and CappingIn this technique, we will do the flooring (e.g., the 10th percentile) for the lower values and capping (e.g., the 90th percentile) for the higher values. The lines of code below print the 10th and 90th percentiles of the variable 'Income', respectively. These values will be used for quantile-based flooring and capping.
python Now we will remove the outliers, as shown in the lines of code below. Finally, we calculate the skewness value again, which comes out much better now.
python TrimmingIn this method, we completely remove data points that are outliers. Consider the 'Age' variable, which had a minimum value of 0 and a maximum value of 200. The first line of code below creates an index for all the data points where the age takes these two values. The second line drops these index rows from the data, while the third line of code prints summary statistics for the variable. After trimming, the number of observations is reduced from 600 to 594, and the minimum and maximum values are much more acceptable.
python
IQR ScoreThis technique uses the IQR scores calculated earlier to remove outliers. The rule of thumb is that anything not in the range of (Q1 - 1.5 IQR) and (Q3 + 1.5 IQR) is an outlier, and can be removed. The first line of code below removes outliers based on the IQR range and stores the result in the data frame 'df_out'. The second line prints the shape of this data, which comes out to be 375 observations of 6 variables. This shows that for our data, a lot of records get deleted if we use the IQR method.
python Log TransformationTransformation of the skewed variables may also help correct the distribution of the variables. These could be logarithmic, square root, or square transformations. The most common is the logarithmic transformation, which is done on the 'Loan_amount' variable in the first line of code below. The second and third lines of code print the skewness value before and after the transformation.
python
The above output shows that the skewness value came down from 2.8 to -0.18, confirming that the distribution has been treated for extreme values. Replacing Outliers with Median ValuesIn this technique, we replace the extreme values with median values. It is advised to not use mean values as they are affected by outliers. The first line of code below prints the 50th percentile value, or the median, which comes out to be 140. The second line prints the 95th percentile value, which comes out to be around 326. The third line of code below replaces all those values in the 'Loan_amount' variable, which are greater than the 95th percentile, with the median value. Finally, the fourth line prints summary statistics after all these techniques have been employed for outlier treatment.
python
ConclusionIn this guide, you have learned methods of identifying outliersusing bothquantitative and visualization techniques. You have also learnedtechniques for treating the identified outliers. Your usage of these techniques will depend on the data, the problem statement, and the machine learning algorithm selected for building the model. To learn more about data preparation and building machine learning models using Python, please refer to the following guides: To learn more about building deep learning models using Keras, please refer to the following guides: Can you replace outliers with mean?in this technique, we replace the extreme values with the mode value, you can use median or mean value but it is advised not to use the mean values because it is highly susceptible to outliers.
How do you replace outliers in Python?Using IQR, we can follow the below approach to replace the outliers with a NULL value:. Calculate the first and third quartile (Q1 and Q3).. Further, evaluate the interquartile range, IQR = Q3-Q1.. Estimate the lower bound, the lower bound = Q1*1.5.. Estimate the upper bound, upper bound = Q3*1.5.. How do you replace outliers in multiple columns in Python?“pandas remove outliers for multiple columns” Code Answer. def cap_data(df):. for col in df. columns:. print("capping the ",col). if (((df[col]. dtype)=='float64') | ((df[col]. ... . percentiles = df[col]. ... . df[col][df[col] <= percentiles[0]] = percentiles[0]. df[col][df[col] >= percentiles[1]] = percentiles[1]. How do you replace outliers using IQR in Python?Outlier detection using IQR method and Box plot in Python. # method 1. Q1 = np.percentile(grades , 25) Q3 = np. ... . IQR = Q3 - Q1. ul = Q3+1.5*IQR. ll = Q1-1.5*IQR. ... . outliers = grades[(grades > ul) | (grades < ll)] outliers. ... . fig = plt.figure(figsize=(6,5)) hypo = np.random.randint(20, 81, size=500). |