[Numpy-discussion] Is there a memory-efficient alternative to choose?

Lutz Maibaum lutz.maibaum at gmail.com
Tue Mar 8 16:53:52 EST 2011

On Mar 8, 2011, at 11:56 AM, Josh Hykes wrote:
> At some point in my code, I need to do a cell-wise multiplication of the properties with a state variable. The ideal method would (1) be fast (no Python loops) and (2) not waste memory constructing an entire property map. My best attempt using choose does (1) but not (2).

Would the "out" keyword of np.choose be a possible solution? Using that, you should be able to create the properies_map in place, and perhaps you can then do the multiplication with the state variables in place also:

import numpy as np
properties = {0: 0.5, 1: 2.} # 2 materials
mesh_map = np.array([[0,0,0,0], [0,1,1,0], [0,1,1,0], [0,0,0,0]]) # 4x4 mesh
state_variables = np.arange(mesh_map.size).reshape(mesh_map.shape) # fake state variables
answer = np.empty (mesh_map.shape, np.float)  # do this only once with dtype of properties
np.choose(mesh_map, (properties[0], properties[1]), out=answer)
answer[:] = answer * state_variables

Hope this helps,


More information about the NumPy-Discussion mailing list