Let’s see how to calculate mode in Python.
Mode in Python
To calculate mode we need to import statistics module.
Luckily there is dedicated function in statistics module to calculate mode.
import statistics as s x = [1, 5, 7, 5, 8, 43, 6] mode = s.mode(x) print("Mode equals: " + str(mode))
Mode in Numpy
It was how to calculate mode in Python. However it is also a possibility to calculate mode with Numpy Python library.
import numpy as np my_array = np.array([1, 2, 4, 4, 7, 7, 7, 20]) mode = np.argmax(np.bincount(my_array)) print(f"Mode equals: {mode}")
Thanks to this mode = np.argmax(np.bincount(my_array)) easy trick mode has been calculated.