Archive for the 'NumPy' Category

Sort one list by another list

Here are a couple of ways of sorting one list by another list in Python. The first uses plain ol’ Python, and the others use NumPy.

In each case imagine we want to sort a list of peoples names by their ages. Continue reading ‘Sort one list by another list’

Convert None to NaN for use in NumPy arrays

I originally had the function below to convert values of None into values of NaN, but realized it is much faster and easier to coerce the array type:

x.astype(float)

Here’s the slow way to do it:

from numpy import array, nan
def None2NaN(x):
    """Converts None objects to nan, for use in
       NumPy arrays. Returns an array."""
    newlist = []
    for i in x:
        if i is not None:
            newlist.append(i)
        else:
            newlist.append(nan)
    return array(newlist)

“Vectorization” in NumPy

How do you get Matlab-like vectorization when using NumPy? The key is using parentheses when using logical operators. Here’s an example:

from numpy import *

a = array([1,2,3,4,5])
b = array([5,4,3,2,1])
c = array([1,2,2,2,1])

# ===The right way===

(a<5) & (b>3) & (c==2)
# array([ False,  True, False, False, False], dtype=bool)

# ===The wrong way===

a<5 & b>3 & c==2
# ValueError:
# The truth value of an array with more than
# one element is ambiguous. Use a.any() or a.all()

Alternatively, use NumPy’s logical_and and logical_or functions . . . but these functions only take two arguments at a time.

NumPy arrays vs Matlab matrices

NumPy has the same functionality as Matlab in terms of arrays (maybe a little more) but there are some syntax differences in creating and indexing arrays that confused me at first when switching from Matlab to NumPy. Continue reading ‘NumPy arrays vs Matlab matrices’