-1

Suppose I have a numpy array

a = np.array([0,2,3,4,5,1,9,0,0,7,9,0,0,0]).reshape(7,2)

I want to find out the indices of all the times the minimum element (here 0) occurs in the 2nd column. Using argmin I can find out the index of when 0 is occurring for the first time. How can I do this in Python?

m00am
  • 5,910
  • 11
  • 53
  • 69
Bidisha Das
  • 177
  • 2
  • 11
  • 1
    Welcome to StackOverflow. You are currently simply expecting us to solve the problem **for you**. **PLEASE** give it a try **on your own**, and if you have no clue please search online and learn the basics and then show us what you've achieved - and if you get stuck along the way, feel free to come back and ask for help. – Hearen Jul 19 '18 at 07:54
  • Possible duplicate with https://stackoverflow.com/q/6294179/9303824 – Kay Wittig Jul 19 '18 at 07:57

2 Answers2

1

Using np.flatnonzero on a[:, 1]==np.min(a) is the most starightforward way:

In [3]: idxs = np.flatnonzero(a[:, 1]==np.min(a))

In [4]: idxs
Out[4]: array([3, 5, 6])
kuppern87
  • 1,125
  • 9
  • 14
0

After you reshaped your array it looks like this:

array([[0, 2],
       [3, 4],
       [5, 1],
       [9, 0],
       [0, 7],
       [9, 0],
       [0, 0]])

You can get all elements that are of the same value by using np.where. IN your case the following would work:

np.where(a.T[-1] == a.argmin())
# This would give you (array([3, 5, 6]),)

What happens here is that you create a transposed view on the array. This means you can easily access the columns. The term view here means that the a array itself is not changed for that. This leaves you with:

a.T

array([[0, 3, 5, 9, 0, 9, 0],
       [2, 4, 1, 0, 7, 0, 0]])

From this you select the last line (i.e. the last column of a) by using the index -1. Now you have the array

array([2, 4, 1, 0, 7, 0, 0])

on which you can call np.where(condititon), which gives you all indices for which the condition is true. In your case the condition is

a.T[-1] == a.argmin()

which gives you all entries in the selected line of the transposed array that have the same value as np.argmin(a) which, as you said, is 0 in your case.

m00am
  • 5,910
  • 11
  • 53
  • 69
  • 1
    Why do you need the explicit `.view()`? Doesn't numpy create views automatically? (transpose is also a view AFAIK). – clemisch Jul 19 '18 at 09:07
  • You're welcome. Please consider accepting an answer to your question by clicking on the tick mark next to the up/ downvote arrows. This marks your question as resolved. – m00am Jul 19 '18 at 11:40