Skip to content

Instantly share code, notes, and snippets.

@mwaskom
Created July 26, 2013 21:58
Show Gist options
  • Save mwaskom/6092547 to your computer and use it in GitHub Desktop.
Save mwaskom/6092547 to your computer and use it in GitHub Desktop.
Simple example of some array manipulations
# from <module> import * is strongly discouraged
import numpy as np
# One way to make your array that shows off a few features
# Specifying it like you did is fine, but why bother?
a = np.arange(1, 7)
a[1::2] *= -1
# Again, just demonstrating some features
choice = np.array([np.ones(6),
range(1, 7)])
choice[0, -3:] = -1
# Show the arrays we ended upwith
print "a: \n", a
print "choice: \n", choice
# We want to count how many elements of `a` are > 0
# when the first row of `choice` is 1
# In one line
print "One-liner: ", (a[choice[0] == 1] > 0).sum()
# A bit more didactically
mask = choice[0] == 1
a_vals = a[mask]
a_pos = a_vals > 0
a_sum = a_pos.sum()
print "Didactic: ", a_sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment