ErwinU
ErwinU

Reputation: 31

Numpy: Get rid of loop in a concrete example

I'm new to Numpy and already read a few things about it. Repeatedly it says, that you should get rid of loops when using Numpy, because otherwise you have some Python-overhead which slows down your code. So for practicing I tried to implement a simple algorithm in a "numpythonic" way, but I can't manage to get rid of the for loop. Is there a way to improve this solution?

My main problem is, that I have some kind of "cumulative-conditional" situation and I have no idea how I can solve this without a loop.

import numpy as np

def process(data):
    r = np.zeros(3)
    for d in data:
        ru = r / np.linalg.norm(r)
        r = np.where(
            np.dot(ru, d) < 0.0,
            r + np.negative(d),
            r + d
        )    
    return r

data = [
    [0.99558784, 0.03476669, -0.08715574],
    [0.99194152, 0.1217951, -0.0348995],
    [0.9864998, 0.08630755, -0.1391731]
]

print(process(data))
# Out: [ 2.97402916  0.24286934 -0.26122834]

(Besides of my main problem I'm open for general criticism or improvement suggestions of course)

Upvotes: 3

Views: 82

Answers (1)

rpoleski
rpoleski

Reputation: 998

A few comments:

  1. In first loop, your ru = ... statement produces warning - it divides by 0.
  2. In this case, np.dot() returns a single float, not an array. Hence, there is no point for using np.where(); if statement would be faster.
  3. For the data you provided, your function is equivalent to np.sum(data, axis=0).

Upvotes: 2

Related Questions