This post summarises my solution to this NumPy Fancy Indexing Exercise (Challenge 3) – originated from scipy-lectures.org
The Problem
Generate a 10 x 3 array of random numbers (in range [0,1]). For each row, pick the number closest to 0.5.
- Use
absandargsortto find the column j closest for each row. - Use fancy indexing to extract the numbers. (Hint:
a[i,j]– the arrayimust contain the row numbers corresponding to stuff inj.)
The Solution
First version code to illustrate how things work:
Now we know how things work, let’s compact the solution (optional).
Major Learning Summary
- Fancy Indexing –
a[rows, cols]ora[[1, 2, 3, 4], [2, 1, 0, 1]] - Sorting –
sort,argsort,argmin/argmax.