Skip to content

Instantly share code, notes, and snippets.

@fcostin
Created June 7, 2012 07:04
Show Gist options
  • Save fcostin/2887052 to your computer and use it in GitHub Desktop.
Save fcostin/2887052 to your computer and use it in GitHub Desktop.
python & numpy port of james hague's blog post 141
"""
python & numpy port of james hague's blog post 141
ref:
http://prog21.dadgum.com/141.html
"""
import numpy
a = numpy.array([10, 5, 9, 6, 20, 17, 1])
print(a)
# slice into `a` using array of indices
print(a[[0, 1, 3, 6]])
# drop first two elements, slicing with explicit array of indices
print(a[[2, 3, 4, 5, 6]])
# drop first two elements, slicing with boolean mask array
print(a[numpy.array([False, False, True, True, True, True, True], dtype = numpy.bool)])
# drop first two elements using nice pythonic slice syntax
print(a[2:])
# permute arrays `a` and `b` to sort a, keeping them in synch
b = numpy.array([101, 51, 91, 61, 201, 171, 11])
print(a)
print(b)
order = numpy.argsort(a)
# check that argsort does what we expect
assert numpy.all(a[order] == numpy.sort(a))
print(a[order])
print(b[order])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment