Arun Abraham
Arun Abraham

Reputation: 4047

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

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.

Upvotes: 3

Views: 89

Answers (1)

Bi Rico
Bi Rico

Reputation: 25833

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

Upvotes: 2

Related Questions