Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "freq" function in numpy/python? [duplicate]

Tags:

python

numpy

Suppose you have:

arr = np.array([1,2,1,3,3,4])

Is there a built in function that returns the most frequent element?

like image 733
lord12 Avatar asked Mar 31 '13 21:03

lord12


People also ask

What is NumPy used for in Python?

Overview of NumPy Functions Numpy is a python package used for scientific computing. So certainly, it supports a vast variety of functions used for computation. The various functions supported by numpy are mathematical, financial, universal, windows, and logical functions.

Is there a frequency function in Python?

python: is there a frequency function? The Excel FREQUENCY function This useful function can analyse a series of values and summarise them into a number of specified ranges. For example the heights of some children can be grouped in to four categories of [Less than 150cm]; [151 - 160cm]; [161 - 170cm]; [More than 170cm].

How to count the frequency of unique values in NumPy array?

Let’s see How to count the frequency of unique values in NumPy array. Python’s numpy library provides a numpy.unique() function to find the unique elements and it’s corresponding frequency in a numpy array. Syntax: numpy.unique(arr, return_counts=False)

How to find unique elements in a NumPy array in Python?

Python’s numpy library provides a numpy.unique () function to find the unique elements and it’s corresponding frequency in a numpy array. Return: Sorted unique elements of an array with their corresponding frequency counts NumPy array.


2 Answers

Yes, Python's collections.Counter has direct support for finding the most frequent elements:

>>> from collections import Counter

>>> Counter('abracadbra').most_common(2)
[('a', 4), ('r', 2)]

>>> Counter([1,2,1,3,3,4]).most_common(2)
[(1, 2), (3, 2)]

With numpy, you might want to start with the histogram() function or the bincount() function.

With scipy, you can search for the modal element with mstats.mode.

like image 69
Raymond Hettinger Avatar answered Nov 01 '22 05:11

Raymond Hettinger


the pandas module might also be of help here. pandas is a neat data analysis package for python and also has support for this problem.

import pandas as pd 
arr = np.array([1,2,1,3,3,4])
arr_df = pd.Series(arr) 
value_counts = arr_df.value_counts()
most_frequent = value_counts.max()

this returns

> most_frequent 
2 
like image 39
cantdutchthis Avatar answered Nov 01 '22 03:11

cantdutchthis