This short tutorial will teach how to use Python for the median of the list and set and how to use Numpy to find the median of an array – matrix columns and rows.
Python Median of List
In python, you can use the native module statistics and import median to compute the median of a list or set as we show below
import statistics
my_list = [1, 2, 3, 4]
list_median = statistics.median(my_list)
my_set = {1, 2, 3, 4}
set_median = statistics.median(my_set)
print("The List Median is {}".format(list_median))
print("The Set Median is {}".format(set_median))
Which should print
The List Median is 2.5
The Set Median is 2.5
Numpy Median of Array – Matrix
In case you need to find the median for the columns or rows of a matrix, you can use numpy.
import numpy
# create matrix
my_matrix = [[1, 2, 3, 4], [1, 1, 1, 1]]
# axis=1 will find the median for the rows
matrix_rows_median = numpy.median(my_matrix, axis=1)
# axis=0 will find the median for the columns
matrix_columns_median = numpy.median(my_matrix, axis=0)
print("The Matrix rows Medians are {}".format(matrix_rows_median))
print("The Matrix Columns Medians are {}".format(matrix_columns_median))
which should print
The Matrix rows Medians are [2.5 1. ]
The Matrix Columns Medians are [1. 1.5 2. 2.5]
More Resources
Here are three of my favorite Python Books in case you want to learn more about it.
- Python Cookbook, Third Edition by David Beazley and Brian K. Jones
- Learning Python, 5th Edition Fifth Edition by Mark Lutz
- Python Pocket Reference: Python In Your Pocket by Mark Lutz