NumPy Exercise – Argsort and Fancy Indexing

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 abs and argsort to find the column j closest for each row.
  • Use fancy indexing to extract the numbers. (Hint: a[i,j] – the array i must contain the row numbers corresponding to stuff in j.)

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 Indexinga[rows, cols] or a[[1, 2, 3, 4], [2, 1, 0, 1]]
  • Sortingsort, argsort, argmin / argmax.