Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i do this numpy array operation in an efficient manner?

Tags:

python

numpy

I am new to python.

If i have a (m x n) array, how can i find which column has the maximum repetitions of a particular value eg. 1 ? Is there any easy operation rather than writing iterative loops to do this.

like image 769
Arun Abraham Avatar asked Dec 11 '25 07:12

Arun Abraham


1 Answers

Welcome to python and numpy. You can get the column with the most 1s by first checking which values in your array are 1, then counting that along each column and finally taking the argmax. In code it looks something like this:

>>> import numpy as np
>>> (m, n) = (4, 5)
>>> a = np.zeros((m, n))
>>> a[2, 3] = 1.
>>>
>>> a_eq_1 = a == 1
>>> repetitions = a_eq_1.sum(axis=0)
>>> np.argmax(repetitions)
3

Or more compactly:

>>> np.argmax((a == 1).sum(axis=0))
3
like image 158
Bi Rico Avatar answered Dec 12 '25 20:12

Bi Rico