Python NumPy Median + Examples

In this Python NumPy tutorial, we will learn how to get the median using the NumPy array in Python. With the Python NumPy median function, we will cover these topics.

  • Python numpy median filter
  • Python numpy median absolute deviation
  • Python numpy median example
  • Python numpy median ignore nan
  • Python numpy median 2d array
  • Python np.median axis
  • Python numpy weighted median
  • Python median without numpy
  • Python numpy mean squared error
  • Python numpy mean absolute error
  • Python numpy mean of empty slice
  • Python numpy mean of each column
  • Python np.mean round
  • Python numpy root mean square
  • Python numpy reduce mean
  • Python numpy mean and standard deviation
  • Python numpy harmonic mean
  • Python numpy mean ignore zero
  • Python numpy average vs mean

Python numpy median

  • In this section, we will discuss how to find the median of a numpy array in Python.
  • To do the task we are going to use the Python numpy.median() function. In Python, this is a mathematical function and it is used to compute the median of the elements in an array.
  • This method is available in the NumPy package module and always returns the median of the numpy array value as an output. If you are using a multidimensional array then you can also get the median value of each column and row.

Syntax:

Let’s have a look at the Syntax and understand the working of Python numpy.median() function

numpy.median
            (
             a,
             axis=None,
             out=None,
             overwrite_input=False,
             keepdims=False
            )
  • This Syntax contains several parameters
    • a: This parameter specifies the input array on which we want to operate on.
    • axis: This parameter indicates the axis which we want to calculate the median along with the flattened input array. If the axis is 0 then the direction down the rows and if the axis is 1 then the direction down column-wise.
    • out: It is an optional parameter and it is used to store the result of numpy.median() function and by default it takes none value.
    • keepdims: This parameter defines the dimension of the input array and if the value is ‘True’ the axes which are reduced are left in the output.

Example:

Let’s take an example and check how to use the numpy.median() function in Python

Source Code:

import numpy as np

new_arr=np.array([67,89,113,145,167])
new_output= np.median(new_arr)
print("Median of an array:",new_output)

In the above code, we imported the numpy library and then initialize an array by using the numpy.array() function and now we have to find the median of the input array. To do this we are going to use the numpy.median() function.

In the above array, we have an odd number of terms in ascending order. It will calculate the array median=middle term.

Here is the implementation of the following given code

Python numpy median
Python numpy median

Also, check: Python NumPy Count – Useful Guide

Python numpy median filter

We had already covered this topic in the Python NumPy filter article. You can easily get all the information regarding Python numpy median filter.

Python numpy median absolute deviation

  • In Python, the numpy median absolute deviation is used to measure the observation in a given array.
  • To calculate the median absolute deviation we can easily use the mad=median(|xi-xm|) where xi is the data and xm is the median value.

Example:

import numpy as np

new_arr = ([17, 23, 55, 61, 63, 65,  71, 83])
new_result=np.median(np.absolute(new_arr - np.median(new_arr)))
print(new_result)

Here is the Screenshot of the following given code

Python numpy median absolute deviation
Python numpy median absolute deviation

Read: Python NumPy Replace + Examples

Python numpy median example

  • In this section, we will discuss how to use the numpy.median() function in Python.
  • In Python, the numpy median is used to generate the median value in the NumPy array and this function involves many parameters namely axis. keepdims and it is also used for specifying the data type that a user needs to be operand on.
  • In this example, we will use the axis and keepdims parameter to check how to get the median value of the numpy array.

Example:

Let’s take an example and check how to use the numpy.median() function in Python

Source Code:

import numpy as np

new_arr=np.array([[67,89,113,145,167],
                 [14,16,18,20,24],
                 [33,45,67,89,91]])
new_output= np.median(new_arr,axis=0)
new_output2= np.median(new_arr,axis=1,)
print("Axis row-wise median:",new_output)
print("Axis column-wise median",new_output2)

In the above program, we have used the axis parameter in numpy.median() function and it will calculate the row and column medians.

Here is the execution of the following given code

Python numpy median example
Python numpy median example

Read: Python NumPy Add Tutorial

Python numpy median ignore nan

  • In this section we will learn how to calculate median of numpy array and ignore nan values in Python.
  • To do this task we are going to use the numpy.nanmedian() function. This function will help the user to return the median of array value while ignoring nan values.
  • This method is available in the NumPy package module and it involves several parameters and it calculates the median along with the axis.

Syntax:

Here is the Syntax of Python numpy.nanmedian() function

numpy.nanmedian
               (
                a,
                axis=None,
                out=None,
                overwrite_input=False,
                keepdims=<no value>
               )

Example:

Let’s take an example and check how to use the numpy.nanmedian() function in Python

Source Code:

import numpy as np

new_arr=np.array([67,89,np.nan,145,np.nan])
new_output= np.nanmedian(new_arr)
print(new_output)

Here is the Output of the following given code

Python numpy median ignore nan
Python numpy median ignore nan

Read: Python NumPy diff with examples

Python numpy median 2d array

  • Here we can see how to calculate median in Python 2-dimensional array.
  • In this example, we are going to calculate the median of the array, To do this task first we will create an array by using the numpy.array() function. Now we will specify the axis to be 1 and it will find out the median for the input array.

Syntax:

Here is the Syntax of Python numpy.median() function

numpy.median
            (
             a,
             axis=None,
             out=None,
             overwrite_input=False,
             keepdims=False
            )

Example:

import numpy as np

values=np.array([[10,12,14,18,26],
                [24,26,28,30,40]])
print("Creation of two-dimensional array:",values)
new_result= np.nanmedian(values,axis=1)
print(new_result)

Here is the Screenshot of the following given code.

Python numpy median 2d array
Python numpy median 2d array

Also, check: Python NumPy 2d array

Python np.median axis

  • In this section we will discuss how to use axis parameter in Python numpy.median() function.
  • In this example, we are going to compute the row and column medians by using the axis parameter. If the axis =0 then it effectively computes the column medians and if the axis=1 then it will display the row medians.

Example:

import numpy as np

new_arr=np.array([[14,24,34,44,64],
                 [9,13,17,21,25],
                 [33,45,67,89,91]])
dis_row= np.median(new_arr,axis=0)
dis_col= np.median(new_arr,axis=1,)
print("Axis row-wise median:",dis_row)
print("Axis column-wise median",dis_col)
Python np median axis
Python np median axis

Read: Python NumPy Data types

Python numpy weighted median

  • In this program, we will discuss how to calculate the weighted average median of a Python NumPy array.
  • To perform this particular task we are going to use the np.cumsum() method. In Python, the numpy.cumsum() is used to generate the cumulative sum of numpy values. Next, we will use the np.searchsorted() function and it is used to find the indices of a value while inserting it into a sorted numpy array.
  • After that, we have declared a variable ‘weights’ and assigned the list comprehension method. Once you will print ‘weights’ it will display the numpy array weighted median values.

Syntax:

Here is the Syntax of Python numpy.cumsum() function

numpy.cumsum
            (
             a,
             axis=None,
             dtype=None,
             out=None
            )
  • It consists of a few parameter
    • a: This parameter indicates the input array.
    • axis: By default it takes none value and it used to compute the cumsum over the array.
    • dtype: It is an optional parameter and if it is not specified then it takes integer value.

Example:

import numpy as np

new_arr = np.array([[16, 278, 34, 41], [83, 38, 19, 10], [35,78,92,35], [104,245,943,145], [234,789,432,190]])

z = np.cumsum(new_arr, axis=1) 
new_ind = [np.searchsorted(row, row[-1]/2.0) for row in z]
weights = [m * 10 for m in new_ind] 

print("median masses is:",  weights)
print(new_arr)
print(np.hstack((z, z[:, -1, np.newaxis]/2.0)))

You can refer to the below Screenshot

Python numpy weighted median
Python numpy weighted median

Read: Python NumPy Delete

Python median without numpy

  • In this section, we will discuss how to get the median value in Python without using numpy.
  • To do this task we are going to use the Python median() function. This function takes a sample value and returns its median without sorting its list.
  • For example, suppose we have a list that contains employees id numbers. now we want to calculate the median of a list of numbers. To do this task we are going to use statistics.median() function. The mathematical formula for the median is {(n+1)/2}.

Syntax:

Here is the Syntax of Python statistics.median()

statistics.median(data)

Example:

Let’s take an example and check how to find the median value in Python without using numpy.

Source Code:

import statistics

employee_id = [16, 7, 15, 23, 89, 56, 67, 10, 24, 36, 57, 19]
new_median_value = statistics.median(employee_id)
print("Medain value of employees id:",new_median_value)

In the following given code, we imported the statistics module and then initialize a list. After that, we have used the statistics.median() function and within this function, we have assigned the list ’employee_id’. Once you will print ‘new_median_value’ then the result will display the median value.

Here is the execution of the following given code

Python median without numpy
Python median without numpy

Read: Python Numpy Not Found – How to Fix

Python numpy mean squared error

  • In this section, we will discuss how to calculate the mean squared error in Python numpy array.
  • In this example we have to find the mean of error squares basically square errors is between the estimated values and the true values. It is also called a regression problem.
  • In this example, we have to find the regression line for the below-given values. In Python, we can easily find the regression line by using y=mx+c where y values will be the predicted value.
  • You have to insert the random values in the ‘x’ variable for generating the ‘y’ values. we have used [7,8,9,4,3] values and then use the np.square() function and within this function, we get the difference between true values and predicted values.
  • Mathematic formula to calculate the mean squared error is
MSE = (1/n)∑i=1n
 (Xobs,i -Xmodel,i)²   

Source Code:

import numpy as np

new_values_true= [6,12,15,17,18]
new_values_predict= [4.4,4.8,5.2,3.2,2.8]
new_result = np.square(np.subtract(new_values_true,new_values_predict)).mean()
print("Mean squared error:",new_result)

In the following given code, we imported the numpy library and then declare two variables ‘new_values_true’ and ‘new_values_predict’. It indicates the original value and calculated value

Here is the Screenshot of the following given code.

Python numpy mean squared error
Python numpy mean squared error

Read: Python NumPy Minimum tutorial

Python numpy mean absolute error

  • In this section, we will discuss how to calculate the mean of the absolute error in the Python numpy array.
  • To perform this particular task we are going to use the np.absolute() function to get the absolute sign in the mean absolute error and this method will calculate the absolute value element-wise.
  • In this example, we have used the np.sum() function for summing all the elements.

Syntax:

Here is the Syntax of Python numpy.absolute() function

numpy.absolute
              (
               x,
               /,
               out=None,
               *,
               where=True,
               casting='same_kind',
               order='K',
               dtype=None,
              )

Example:

import numpy as np

arr1=np.array([23,34,56,78,9])
arr2= np.array([14,23,67,8,17])
result = np.sum(np.absolute((arr1 - arr2)))
print("Mean absolute error:",result.astype("int"))

You can refer to the below Screenshot

Python numpy mean absolute error
Python numpy mean absolute error

Read: Python NumPy Stack with Examples

Python numpy mean of empty slice

  • In this Program we will solve the runtime error warning ‘mean of empty slice’ in Python
  • In this example, we have used the concept of numpy.nanmean() function. In Python, this function is used to calculate the mean of the numpy array and ignore the nan values.
  • In this Program, we have created a simple numpy array by using the numpy.array() function and assign np.nan values.

Syntax:

Here is the Syntax of numpy.nanmean() function

numpy.nanmean
             (
              a,
              axis=None,
              dtype=None,
              out=None,
              keepdims=<no value>
             )

Example:

import numpy as np

new_arr = np.array([np.nan, np.nan,np.nan])
new_result = np.nanmean(new_arr)
print("Calculate mean:",new_result)

In the following given code, we have used to np.nanmean() function and within this function, we have passed array as an argument.

Here is the implementation of the following given code.

Python numpy mean of empty slice
Python numpy mean of empty slice

As you can see in the Screenshot the output displays the runtime warning ‘Mean of empty slice’.

Solution

Here is the Solution of runtime warning ‘Mean of empty slice’

  • In this example, we are going to update the input array like we will insert the integer number in it.
  • The reason for the run-time error is we have not inserted the integer values. While using numpy.nanmean() function you have to use at least one non-nan value.

Source Code:

import numpy as np

new_arr = np.array([12,13,np.nan, np.nan,np.nan])
new_result = np.nanmean(new_arr)
print("Calculate mean:",new_result)

Here is the implementation of the following given code.

Solution of Python numpy mean of empty slice
Solution of Python numpy mean of empty slice

Read: Python NumPy round + 13 Examples

Python numpy mean of each column

  • In this section, we will discuss how to calculate the mean of each column in Python numpy array.
  • In Python to compute the mean of values in a Numpy array then we can easily use the numpy.mean() function. This function takes the sum of all elements available in an array along with the axis and is divided by the number of elements.
  • This method is available in the Numpy package module and returns the mean of the array elements. In this example we will use the axis parameter enables to calculate the mean of the column. If the axis is 1 then the direction goes horizontally across the column.

Syntax:

Here is the Syntax of Python numpy.mean() function

numpy.mean
          (
           a,
           axis=None,
           dtype=None,
           out=None,
           keepdims=<no value>,
           where=<no value>
          )

Example:

Let’s take an example and check how to calculate the mean of each column in Python numpy array

Source Code:

import numpy as np

new_arr = np.array([[14,25,36,37],
                    [15,16,27,37]])
new_output = np.mean(new_arr,axis=1)
print("Calculate mean column-wise:",new_output)

Here is the implementation of the following given code

Python numpy mean of each column
Python numpy mean of each column

As you can see in the Screenshot the output displays the mean value of the array column-wise.

Read: Python NumPy Repeat

Python np.mean round

  • In this section, we will discuss how to round off the mean value in the Python NumPy array.
  • To perform this particular task firstly we will create an array and use the np.mean() function. Once you will print ‘new_output’ then the result will display the mean value of the array.
  • After that, we are going to use the numpy.round() function and get the rounded value of mean values.

Example:

Let’s take an example and check how to use the Python numpy.round() function.

Source Code:

import numpy as np

new_arr = np.array([12,34,56,78,54])
new_output = np.mean(new_arr)
print("Calculate mean of array:",new_output)
d= np.round(new_output)
print("Rounded value of mean:",d)

In the above program, we have created an array by using the numpy.array() function that contains integer value. After that, we have assigned a mean value result in numpy.round() function as an argument.

Here is the Screenshot of the following given code.

Python np mean round
Python np mean round

Read: Python NumPy 3d array + Examples

Python numpy root mean square

  • In this section, we will discuss how to calculate the root mean square value in Python numpy array.
  • To do this task we are going to use the numpy.sqrt() function. In this example, this function takes the numpy array to mean as an argument and calculates the square root of elements in the array.

Example:

import numpy as np

new_arr= np.array([12,14,16,18,20])
result=np.mean(new_arr**2)
print("Mean array:",result)
new_roo= np.sqrt(result)
print(new_roo)

You can refer to the below Screenshot

Python numpy root mean square
Python numpy root mean square

As you can see in the Screenshot the output displays the square root of a mean value.

Read: Python NumPy Split + 11 Examples

Python numpy reduce mean

  • In this Program, we will learn how to use the numpy.mean() function in Python.
  • In Python the numpy.mean() function is used to find the mean of values in a Numpy array and it also sums all the elements available in an array along with the axis and is divided by the number of elements.

Syntax:

Here is the Syntax of Python numpy.mean() function

numpy.mean
          (
           a,
           axis=None,
           dtype=None,
           out=None,
           keepdims=<no value>,
           where=<no value>
          )

Example:

import numpy as np

new_values= np.array([16,23,26,29,30])
new_output =np.mean(new_values)
print("Mean value:",new_output)

Here is the output of the following given code

Python numpy reduce mean
Python numpy reduce mean

Read: Python NumPy Normalize

Python numpy mean and standard deviation

  • In this section, we will learn how to calculate the standard deviation in Python numpy array by using the numpy.std() function.
  • In Python, this function will help the user to measure the amount of variance in data and also the square root of the mean square deviation.
  • This method is available in the Python numpy package module and always returns the standard deviation of the input array.

Syntax:

Let’s have a look at the Syntax and understand the working of Python numpy.std() function.

numpy.std
         (
          a,
          axis=None,
          dtype=None,
          out=None,
          ddof=0,
          keepdims=<no value>,
          where=<no value>
         )
  • It consists of a few parameters
    • a: This parameter indicates the input array whose values standard deviation is calculated.
    • axis: By default, it takes none value and it is an optional parameter to calculate the standard deviation. It indicates the axis along which the std is calculated.
    • dtype: This parameter indicates the data type and by default, it takes float64 value.
    • out: This parameter specifies the output array where the result is to be stored.
    • ddof: It represents the delta degree of freedom and the divisor is used in compute in N-ddof and by default, ddof takes zero value.

Example:

Let’s take an example and check how to find the standard deviation in the Python NumPy array

Source Code:

import numpy as np

new_values= np.array([7,18,16,14,12])
new_output =np.mean(new_values)
new_output2= np.std(new_values)
print("Mean value:",new_output)
print("Standard deviation:",new_output2)

Here is the execution of the following given code

Python numpy mean and standard deviation
Python numpy mean and standard deviation

Read: Python NumPy Random [30 Examples]

Python numpy harmonic mean

  • In this section, we will discuss how to use harmonic mean in Python numpy array.
  • To perform this particular task we are going to use statistics.harmonic_mean() function. In Python, this function is used to get the sum of the reciprocals of the mean and it is also a type of numerical average.

Example:

import numpy as np
import statistics

arr= np.array([12,23,34,56])
new_output= statistics.harmonic_mean(arr)
print(new_output)

In the following given code, we have imported the numpy and statistics library and then initialize an array by using the numpy.array() function. After that, we have used the statistics.harmonic_mean() function and it will compute the harmonic mean of the provided element.

Here is the Screenshot of the following given code

Python numpy harmonic mean
Python numpy harmonic mean

Read: Python NumPy absolute value with examples

Python numpy mean ignore zero

  • In this section we will discuss how to ignore the zero value in mean array by using NumPy Python.
  • To do this task first we will create an array by using the numpy.array() function. Next, we will declare a variable ‘new_output’ and assign a numpy.mean() function. Once you get the mean value from the array.
  • You can easily use the np.trim_zero() function for ignoring the zero value in the mean result.

Syntax:

Here is the Syntax of Python numpy.trim_zeros() function

numpy.trim_zeros
                (
                 filt,
                 trim='fb'
                )

Example:

import numpy as np

new_arr=np.array([
    [18, 89, 12, 145, 167],
    [0, 0, 0, 0, 0]
    ])

new_output= np.mean(new_arr,axis=1)
print("Mean of an array:",new_output)
d = np.trim_zeros(new_output)

print("Ignore zero values:",d)

Here is the execution of the following given code

Python numpy mean ignore zero

Python numpy average vs mean

We had already covered this topic in Python NumPy Average article. You get all the information regarding the difference between NumPy average and NumPy mean in Python.

Also, take a look at some more Python NumPy tutorials.

In this Python NumPy tutorial, we have learned how to get the median using the NumPy array in Python. Moreover, with the Python NumPy median function, we have covered these topics.

  • Python numpy median filter
  • Python numpy median absolute deviation
  • Python numpy median example
  • Python numpy median ignore nan
  • Python numpy median 2d array
  • Python numpy median image
  • Python np.median axis
  • Python numpy weighted median
  • Python median without numpy
  • Python numpy mean squared error
  • Python numpy mean absolute error
  • Python numpy mean of empty slice
  • Python numpy mean of each column
  • Python np.mean round
  • Python numpy rolling median
  • Python numpy root mean square
  • Python numpy reduce mean
  • Python numpy mean and standard deviation
  • Python numpy harmonic mean
  • Python numpy mean ignore zero
  • Python numpy average vs mean