Wednesday, June 5, 2013

Logical indexing with Numpy

I just discovered one nuance of Python's Numpy package which, given my Matlab background, is a bit unintuitive.

Suppose I have an array of numeric data and I would like to filter out only elements whose values lie between, say, 10 and 60, inclusive. In Matlab, I would do this:
filterData = data(data >= 10 & data <=60)

However, logical operations with Numpy sometimes require special functions. The equivalent expression in Python is
filterData = data[np.logical_and(data >= 10, data <= 60)].

np.logical_and() computes the element-wise truth values of (data >= 10) AND(data <= 60), allowing me to logical index (or fancy index, as pythonistas say) into data.