Python:NumPy .median()
Anonymous contributor
Published May 1, 2024
Contribute to Docs
The .median() function calculates the median value of elements in an array along the specified axis.
Syntax
numpy.median(a, axis=None, out=None, overwrite_input=False, keepdims=False)
a: The array of elements to calculate the median from.axis: The axis or axes along which to calculate the median. By default, it considers the array to be flattened (works on all axes).axis=0works along the column andaxis=1works along the row.out: A different array to place the result. It must have the same shape as the expected result.overwrite_input: A parameter which, ifTrue, allows memory usage of the array for calculations.keepdims: A parameter which, ifTrue, keeps reduced axes in the result as dimensions with size one.
Note: The
aparameter is the only required parameter for this function. All other parameters are optional.
Example
The following example creates an array, then applies a few .median() operations, and returns each result to the console:
import numpy as npa = np.array([[0,1,2],[3,4,5]])print(np.median(a))# Computes the median of the entire arrayprint(np.median(a, axis=0))# Computes the median along the vertical axis (column) of the arrayprint(np.median(a, axis=1))# Computes the median along the horizontal axis (row) of the array
This produces the following output:
2.5[1.5 2.5 3.5][1. 4.]
Codebyte Example
The following example creates a 2-dimensional array of random integers (between 1 and 20) and calculates the median using .median(), demonstrating different uses of the axis parameter:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours