Wednesday, 5 March 2025

The Significance of Mean to calculate central tendency of data

‘Mean’ is the average of a set of data points.

Formula to calculate the mean. 


Here,

  1. μ represents the mean.
  2. xi represents each individual value in the dataset.
  3. n is the total number of values in the dataset.

 

For example, I have the values [1, 2, 3, 4, 5] and mean is calculated like below.

 

Mean = (Sum of all values)/(total number of values)

         = (1 + 2 + 3 + 4 + 5)/5

         = 15 / 5

         = 3

 

Implementation of mean in Python

mean.py

data = [1, 2, 3, 4, 5]

no_of_values = len(data)
sum_of_values = sum(data)
mean = sum_of_values/no_of_values

print(f'data : {data}')
print(f'no_of_values : {no_of_values}')
print(f'sum_of_values : {sum_of_values}')
print(f'mean : {mean}')

Output

data : [1, 2, 3, 4, 5]
no_of_values : 5
sum_of_values : 15
mean : 3.0

Mean is mainly used to get the some idea on central tendency.

 

visualize_central_tendency.py

import matplotlib.pyplot as plt
import numpy as np

# Sample dataset
data = [10, 20, 30, 40, 50, 60]

# Calculate the mean
mean = np.mean(data)

# Create a scatter plot of data points
plt.scatter(data, range(len(data)), label='Data Points', color='blue', marker='o')

# Add a vertical line at the mean
plt.axvline(x=mean, color='red', linestyle='--', label='Mean')

# Add labels and a title
plt.xlabel('Actual value')
plt.ylabel('Index')
plt.title('Scatter Plot with Mean')

# Add a legend
plt.legend()

# Show the plot
plt.show()

 

Output

 


 

Mean is affected by outliers

Mean is affected by outliers (extreme values) in the dataset. If there are extreme outliers present in your dataset, then mean might not represent the central tendency accurately.

 

For example, consider below data.

[10, 20, 30, 40, 50, 100000]

 

We have an extreme value 100000 here which impact the central tendency calculation using mean here. You can depict the same from below figure.

 

mean_outliers.py

 

import matplotlib.pyplot as plt
import numpy as np

# Sample dataset
data = [10, 20, 30, 40, 50, 100000]

# Calculate the mean
mean = np.mean(data)

# Create a scatter plot of data points
plt.scatter(data, range(len(data)), label='Data Points', color='blue', marker='o')

# Add a vertical line at the mean
plt.axvline(x=mean, color='red', linestyle='--', label='Mean')

# Add labels and a title
plt.xlabel('Actual value')
plt.ylabel('Index')
plt.title('Scatter Plot with Mean')

# Add a legend
plt.legend()

# Show the plot
plt.show()

Output




What are the other ways to calculate central tendency?

  1. Median
  2. Mode

 

There are other variants of mean to calculate the central tendency

  1. Weighted mean
  2. Geometric mean
  3. Harmonic mean
  4. Trimmed mean

 


Previous                                                    Next                                                    Home

Rotate element using rotate trasnformation in css

The rotate function in CSS is used to apply a 2D rotation to an element.

Syntax

transform: rotate(angle);

 

Angle specifies the degree of rotation. You can use values in degrees (e.g., 45deg, -90deg) or radians (e.g., 1rad, -1rad).

 

rotate.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rotate Example</title>
    <style>
        .container {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-around;
            align-items: center;
            height: 150px;
            width: 80vw;
            margin: 30px;
            border : 2px solid black
        }
        .box {
            width: 100px;
            height: 100px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            color: white;
            background-color: #333;
            margin: 20px;
            position: relative;
        }
        
        .box:nth-child(1) { transform: rotate(-180deg); }
        .box:nth-child(2) { transform: rotate(135deg); }
        .box:nth-child(3) { transform: rotate(-45deg); }
        .box:nth-child(4) { transform: rotate(-90deg); }
        .box:nth-child(5) { transform: rotate(0deg); }
        .box:nth-child(6) { transform: rotate(45deg); }
        .box:nth-child(7) { transform: rotate(90deg); }
        .box:nth-child(8) { transform: rotate(135deg); }
        .box:nth-child(9) { transform: rotate(180deg); }
    </style>
</head>
<body>
    <div class="container">
        <div class="box" data-angle="-180deg">-180 deg</div>
        <div class="box" data-angle="135deg">135 deg</div>
        <div class="box" data-angle="-45deg">-45 deg</div>
        <div class="box" data-angle="-90deg">-90 deg</div>
        <div class="box" data-angle="0deg">0 deg</div>
        <div class="box" data-angle="45deg">45 deg</div>
        <div class="box" data-angle="90deg">90 deg</div>
        <div class="box" data-angle="135deg">135 deg</div>
        <div class="box" data-angle="180deg">180 deg</div>
    </div>
</body>
</html>

 


 

Previous                                                    Next                                                    Home

Scaling Up, Down: A Simple CSS Hover Effect for Interactive Elements

The scale function in CSS is used to resize an element. You can use it in combination with the :hover pseudo-class to scale an element up when the mouse hovers over it, and return it to its original size when the mouse moves away.

scale-up.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Scale Example</title>
    <style>
        .scale-box {
            width: 100px;
            height: 100px;
            background-color: #3498db;
            transition: transform 0.3s ease;
        }

        .scale-box:hover {
            transform: scale(1.2); /* Scales up by 20% */
        }
    </style>
</head>
<body>
    <div class="scale-box"></div>
</body>
</html>

you can also scale down using the scale function in CSS. The scale function can take any value greater than 0, so you can use a value less than 1 to shrink an element.

For example, to scale down an element to 80% of its original size on hover, you would use scale(0.8).

.scale-box:hover {
    transform: scale(0.8); /* Scales down to 80% of the original size */
}

 


Previous                                                    Next                                                    Home

Monday, 3 March 2025

Find and replace Outliers using IQR

The Interquartile Range (IQR) Approach is a statistical method used to detect and handle outliers in a dataset. It is based on quartiles, which divide data into four equal parts. The IQR approach is particularly useful because it is resistant to extreme values and works well for skewed distributions.

Step 1: Calculate IQR

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

   

Step 2: Calculate lower and upper bounds using IQR, and threshold. In general, threshold can be between 1.5 to 3.

 

lower_bound = Q1 - threshold * IQR
upper_bound = Q3 + threshold * IQR

 

Step 3: Replace the outliers.

If the column value is less than lower_bound, then replace it with the lower_bound.

 

df[column] = np.where(df[column] < lower_bound, lower_bound, df[column])

If the column value is greater than upper_bound, then replace it with the upper_bound.

 

df[column] = np.where(df[column] > upper_bound, upper_bound, df[column])

Find the below working application.

 

replace_outliers.py

import pandas as pd
import numpy as np

def find_and_replace_outlier_columns(df, threshold=1.5):
    outlier_columns = []
    for column in df.columns:
        if df[column].dtype in [np.int64, np.float64]:
            Q1 = df[column].quantile(0.25)
            Q3 = df[column].quantile(0.75)
            IQR = Q3 - Q1
            lower_bound = Q1 - threshold * IQR
            upper_bound = Q3 + threshold * IQR
            outliers = df[(df[column] < lower_bound) | (df[column] > upper_bound)]
            if not outliers.empty:
                print(f'\nOutliers exists in the column {column}')
                df[column] = np.where(df[column] < lower_bound, lower_bound, df[column])
                df[column] = np.where(df[column] > upper_bound, upper_bound, df[column])


df = pd.DataFrame({
    'a': [1, 2, 3, 4, 5, 6, 7, 32, 64, 128, 256, 1024],
    'b': [1024, 2058, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
})

print(df.describe())

print('\nReplacing outliers with lower and upper bounds')
find_and_replace_outlier_columns(df, 3)
print(df.describe())

 

Output

                a            b
count    12.000000    12.000000
mean    127.666667   261.416667
std     292.352631   637.057220
min       1.000000     1.000000
25%       3.750000     3.750000
50%       6.500000     6.500000
75%      80.000000     9.250000
max    1024.000000  2058.000000

Replacing outliers with lower and upper bounds

Outliers exists in the column a

Outliers exists in the column b
                a        b
count   12.000000  12.0000
mean    68.062500   8.8750
std    107.414455   8.3445
min      1.000000   1.0000
25%      3.750000   3.7500
50%      6.500000   6.5000
75%     80.000000   9.2500
max    308.750000  25.7500

 

 

Previous                                                    Next                                                    Home

How to handle outliers in Data?

Following are most commonly used methods to handle outliers.

a. Remove outliers

It is the simple way. It removes the outliers from dataset. But the problem with this method is, it can reduce the sample size. If there are few outliers that do not impact the dataset size significantly, then you can straightway remove them.

 

b. Replace the outliers with mean, mode or median

Replace the outliers with mean, mode or median. Go through the basic statistics of the data and choose the best one (mean, median or mode) and replace outliers with that.

 

c. Transform the data

Apply some mathematical transformations on the data to reduce outliers.

df['transformed_column'] = np.log(df['original_column'])

 

d. Winsorization

Winsorization replace the outliers with values that are less extreme.

 

Example

lower_limit = df['Column'].quantile(0.05)
upper_limit = df['Column'].quantile(0.95)

 

Any values below the lower_limit will be replaced with the lower_limit and any scores above the upper_limit will be replaced with the upper_limit

 

Replace all the values which are less than lower_limit with lower_limit

df['Column'] = np.where(df['Column'] < lower_limit, lower_limit, df['Column'])

Replace all the values which are hogher than upper_limit with upper_limit

df['Column'] = np.where(df['Column'] > upper_limit, upper_limit, df['Column'])

 

Unlike removing outliers entirely, Winsorization doesn't reduce the sample size.

  

Previous                                                    Next                                                    Home

Modify the position of element using translate function

The translate transformation function in CSS is part of the transform property, which allows you to modify the position of an element. The translate function specifically moves an element from its current position along the X and Y axes.

Syntax

transform: translate(x, y);

 

Where:

 

1.   x is the distance to move the element along the horizontal axis (X-axis). It can be specified in pixels (px), percentages (%), or other units. +ve value move towards right, and -ve value move towards left.

2.   y is the distance to move the element along the vertical axis (Y-axis). Similarly, it can be in pixels (px), percentages (%), or other units.

 

The behavior of the translate function in CSS is relative to the element's current position within its own coordinate system,

 

translate_function.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: blue;
            transform: translate(50px, 100px);
        }

        .box-translateX {
            width: 100px;
            height: 100px;
            background-color: red;
            transform: translateX(250px);
        }

        .box-translateY {
            width: 100px;
            height: 100px;
            background-color: green;
            transform: translate(150px, 10px);
        }
    </style>
</head>
<body>
    <div class="box"></div>
    <div class="box-translateX"></div>
    <div class="box-translateY"></div>
</body>
</html>

 


 

 

Previous                                                    Next                                                    Home