Optimizing if statement check over a numpy value

Jeremy Sanders jeremy at jeremysanders.net
Thu Jul 23 13:42:31 CEST 2015


Heli Nix wrote:

> Is there any way that I can optimize this if statement.

Array processing is much faster in numpy. Maybe this is close to what you 
want

import numpy as N
# input data
vals = N.array([42, 1, 5, 3.14, 53, 1, 12, 11, 1])
# list of items to exclude
exclude = [1]
# convert to a boolean array
exclbool = N.zeros(vals.shape, dtype=bool)
exclbool[exclude] = True
# do replacement
ones = vals==1.0
# Note: ~ is numpy.logical_not
vals[ones & (~exclbool)] = 1e-20

I think you'll have to convert your HDF array into a numpy array first, 
using numpy.array().

Jeremy




More information about the Python-list mailing list