Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
numpy_fancy_2.py
import numpy as np
# sow a fix seed to make trial and error more predictable
np.random.seed(0)
# create a 10 x 3 NumPy array
a = np.random.rand(10,3)
# do the fancy indexing: for each row, extract the element that is closest to 0.5
a2 = a[np.arange(a.shape[0]), np.argsort(np.abs(a - 0.5))[:,0]]
# array([ 0.5488135 , 0.54488318, 0.43758721, 0.52889492, 0.56804456,
# 0.83261985, 0.77815675, 0.46147936, 0.63992102, 0.52184832])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment