Obtaining the median value over a specified axis of a DataFrame
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 as0or `index') or the column (designated as1orcolumns) 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 libraryimport pandas as pd# creating a dataframedf = pd.DataFrame([[1,2,3,4,5],[1,7,5,9,0.5],[3,11,13,14,12]],columns=list('ABCDE'))# printing the dataframeprint(df)# obtaining the median value vertically across rowsprint(df.median())# obtaining the median value horizontally over columnsprint(df.median(axis="columns"))
Explanation
- Line 4: We import the
pandaslibrary. - Lines 7–10: We create a
DataFramedf. - Line 12: We print
df. - Line 15: Using the
median()function, we obtain the median values running downwards across the rows (axis0). We print the result to the console. - Line 18: Using the
median()function, we obtain the median values running horizontally across columns (axis1). We print the result to the console.