Created
July 26, 2013 21:58
-
-
Save mwaskom/6092547 to your computer and use it in GitHub Desktop.
Simple example of some array manipulations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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