Selected Reading

SciPy - median() Method



The SciPy median() method is used to find the median value of an array. The median value separates the upper half from the lower half on a sample data. Mostly, it is used during the data cleaning process.

In the field of data science, it is used to understand the mid-point of a dataset specially when the data may not be symmetrical.

Syntax

Following is the syntax of the SciPy median() method −

median(data)

Parameters

This method accepts only a single parameter −

  • data: This is a simple parameter which holds an integer array.

Return value

This methods returns the float of the input array(median value).

Example 1

Following is the basic SciPy program that shows the usage of median() method.

import numpy as np
from scipy import stats

data = np.array([1, 3, 3, 6, 7, 8, 9, 10])
median_value = np.median(data)
print("Median Value:", median_value)

Output

The above code produces the following result −

Median Value: 6.5

Example 2

Below the program calculates the median of a 2D array along the specified axis (axis=0), using np.median.

import numpy as np
from scipy import stats

data = np.array([[10, 7, 4], [3, 2, 1], [4, 5, 6]])
median_value = np.median(data, axis=0)
print("Median Value along axis 0:", median_value)

Output

The above code produces the following result −

Median Value along axis 0: [4. 5. 4.]

Example 3

Here, we perform the median with NaNs using np.nan within the np.array() and np.nanmedian() to generate the result.

import numpy as np
from scipy import stats

data = np.array([2, 4, np.nan, 6, 8])
median_value = np.nanmedian(data)
print("Median Value with NaNs:", median_value)

Output

The above code produces the following result −

Median Value with NaNs: 5.0
scipy_reference.htm
Advertisements