Selected Reading

SciPy - weighted() Method



The SciPy weighted() method is not considered as a built-in method because it allows various other functions that the user can perform such as weighted means, weighted sums, and weighted operations.

Furthermore, for better clarification we have survey data which might be more reliable and in time series data, the current observation might be given more weight.

Syntax

Following are the varieties of relatable function in SciPy weighted() Method −

sum()
or,
sqrt()
or,
linregress()

Parameters

Below is the explanation of all the above syntaxes −

  • sum(): Calculate the sum on given data.
  • sqrt(): Find the square root of a number.
  • linregress(): It works on linear least-squares regression for the given two sets of measurements.

Return value

It returns the result in form of floay values.

Example 1

Following is the SciPy weighted() Method calculate the average weight of the given data array using specified weights.

import numpy as np
from scipy.stats import hmean

data = np.array([10, 20, 30, 40, 50])
weights = np.array([1.1, 1.2, 1.3, 1.4, 1.5])

avg_weight = np.average(data, weights = weights)
print("Weighted Harmonic Mean:", avg_weight)

Output

The above code produces the following result −

Weighted Harmonic Mean: 31.53846153846154

Example 2

Below the example perform the task of linear regression on the data x and y that considers the specified weights.

from scipy import stats
import numpy as np

x_axis = np.array([11, 12, 13, 14, 15])
y_axis = np.array([26, 37, 58, 79, 100])
weights = np.array([0.5, 0.5, 1, 1, 1])

# Weighted linear regression
slope, intercept, r_value, p_value, std_err = stats.linregress(x_axis, y_axis)
print(f"Slope: {slope}, Intercept: {intercept}")

Output

The above code produces the following result −

Slope: 19.0, Intercept: -187.0

Example 3

This example illustrate the detail description of the data that contain weighted statistics.

import numpy as np

data = np.array([11, 21, 31, 41, 51])
weights = np.array([0.11, 0.12, 0.13, 0.14, 0.15])

# weighted mean
weighted_mean = np.sum(data * weights) / np.sum(weights)

# weighted standard deviation
weighted_std = np.sqrt(np.sum(weights * (data - weighted_mean)**2) / np.sum(weights))

print(f"Weighted Mean: {weighted_mean:.2f}")
print(f"Weighted Standard Deviation: {weighted_std:.2f}")

Output

The above code produces the following result −

Weighted Mean: 3.67
Weighted Standard Deviation: 1.25
scipy_reference.htm
Advertisements