Skip to content

Instantly share code, notes, and snippets.

@Atlas7
Created May 23, 2017 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Atlas7/24055a2b4521944f8db5f35165a27929 to your computer and use it in GitHub Desktop.
Save Atlas7/24055a2b4521944f8db5f35165a27929 to your computer and use it in GitHub Desktop.
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