[Numpy-discussion] Beginner's question

Benjamin Root ben.root at ou.edu
Sat Apr 16 15:12:29 EDT 2011


On Saturday, April 16, 2011, Laszlo Nagy <gandalf at shopzeus.com> wrote:
>
>    Hi All,
>
> I have this example program:
>
> import numpy as np
> import numpy.random as rnd
>
> def dim_weight(X):
>      weights = X[0]
>      volumes = X[1]*X[2]*X[3]
>      res = np.empty(len(volumes), dtype=np.double)
>      for i,v in enumerate(volumes):
>          if v>5184:
>              res[i] = v/194.0
>          else:
>              res[i] = weights[i]
>      return res
>
>
> # TEST
> N = 10
> X = rnd.randint( 1,25, (4,N))
> print dim_weight(X)
>
> I want to implement the dim_weight() function effectively. But I'm not
> sure how to construct a numpy expression that does the same think for me.
>
> I got to this point:
>
> def dim_weight(X):
>      weights = X[0]
>      volumes = X[1]*X[2]*X[3]
>      dweights = volumes/194.0
>      return ( weights[weights>5184] , dweights[weights<=5184] ) # ???
>
> I don't know how to preserve the order of the elements and return the
> result in one array. Maybe I need to do create a matrix multiply matrix?
> But don't know how.
>
> Thanks,
>
>     Laszlo
>
>

I think you want np.where().

Ben Root



More information about the NumPy-Discussion mailing list