Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python

Obtaining the median value over a specified axis of a DataFrame

Onyejiaku Theophilus Chidalu

Overview

The median() function in pandas is used to obtain the median value of the values of a specified axis of the given DataFrame.

Mathematically, median can be defined as the value of a dataset that lies at the midpoint when all the values in the dataset are sorted in ascending or descending order.

Syntax

The median() function takes the syntax shown below:

DataFrame.median(axis=NoDefault.no_default, skipna=True, numeric_only=None, **kwargs)
Syntax for the mean() function in Pandas

Parameter

The median() function takes the following optional parameter values:

  • axis: This represents the name for the row (designated as 0 or `index') or the column (designated as 1 or columns) axis from which to take the median.
  • skipna: This takes a Boolean value. It determines whether null values are to be excluded or not in the calculation of the median.
  • numeric_only: This takes a Boolean value. It determines whether only float, int, or Boolean columns are included in the calculation.
  • **kwargs: This is an additional keyword argument that can be passed to the function.

Example

# A code to illustrate the median() function in Pandas

# importing the pandas library
import pandas as pd

# creating a dataframe
df = pd.DataFrame([[1,2,3,4,5],
                   [1,7,5,9,0.5],
                   [3,11,13,14,12]],
                   columns=list('ABCDE'))
# printing the dataframe
print(df)

# obtaining the median value vertically across rows
print(df.median())

# obtaining the median value horizontally over columns
print(df.median(axis="columns"))
Implementing the median() function

Explanation

  • Line 4: We import the pandas library.
  • Lines 7–10: We create a DataFrame df.
  • Line 12: We print df.
  • Line 15: Using the median() function, we obtain the median values running downwards across the rows (axis 0). We print the result to the console.
  • Line 18: Using the median() function, we obtain the median values running horizontally across columns (axis 1). We print the result to the console.

RELATED TAGS

pandas
python

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring