Back to Browse

Calculate Median in Python (5 Examples) | List, DataFrame Column, Row & by Group | NumPy & pandas

1.2K views
Jul 18, 2022
5:25

How to calculate the median value for a list or the columns of a pandas DataFrame in the Python programming language. More details: https://statisticsglobe.com/calculate-median-python Python code of this video: my_list = [1, 4, 3, 2, 1, 3, 7, 1, 4, 1] # Create example list print(my_list) # Print example list # [1, 4, 3, 2, 1, 3, 7, 1, 4, 1] import numpy as np # Load NumPy library print(np.median(my_list)) # Get median of list # 2.5 import pandas as pd # Load pandas library data = pd.DataFrame({'x1':[6, 2, 7, 2, 1, 5, 3, 4, 2, 7, 5], # Create pandas DataFrame 'x2':range(0, 11), 'group':['A', 'B', 'B', 'C', 'B', 'A', 'A', 'C', 'C', 'B', 'A']}) print(data) # Print pandas DataFrame print(data['x1'].median()) # Get median of one column # 4.0 print(data.median(numeric_only = True)) # Get median of all columns # x1 4.0 # x2 5.0 # dtype: float64 print(data.median(numeric_only = True, axis = 1)) # Get median of rows # 0 3.0 # 1 1.5 # 2 4.5 # 3 2.5 # 4 2.5 # 5 5.0 # 6 4.5 # 7 5.5 # 8 5.0 # 9 8.0 # 10 7.5 # dtype: float64 print(data.groupby('group').median()) # Get median by group # x1 x2 # group # A 5.0 5.5 # B 4.5 3.0 # C 2.0 7.0 Follow me on Social Media: Facebook – Statistics Globe Page: https://www.facebook.com/statisticsglobecom/ Facebook – R Programming Group for Discussions & Questions: https://www.facebook.com/groups/statisticsglobe Facebook – Python Programming Group for Discussions & Questions: https://www.facebook.com/groups/statisticsglobepython LinkedIn – Statistics Globe Page: https://www.linkedin.com/company/statisticsglobe/ LinkedIn – R Programming Group for Discussions & Questions: https://www.linkedin.com/groups/12555223/ LinkedIn – Python Programming Group for Discussions & Questions: https://www.linkedin.com/groups/12673534/ Twitter: https://twitter.com/JoachimSchork Music by bensound.com

Download

0 formats

No download links available.

Calculate Median in Python (5 Examples) | List, DataFrame Column, Row & by Group | NumPy & pandas | NatokHD