Home > Back-end >  How to iterate over a numpy matrix based on a condition of another nump array?
How to iterate over a numpy matrix based on a condition of another nump array?

Time:09-28

I have a matrix X, and the labels to each vector of that matrix as a np array Y. If the value of Y is 1 I want to multiply the vector of matrix X by another vector W. If the value of Y is -1 I want to multiply the vector of matrix X by another vector Z.

I tried the following loop:

for i in X:
    if Y[i] == 1:
        np.sum(np.multiply(i, np.log(w))   np.multiply((1-i), np.log(1-w)))
    elif Y[i] == -1:
        np.sum(np.multiply(i, np.log(z))   np.multiply((1-i), np.log(1-z)))

IndexError: arrays used as indices must be of integer (or boolean) type

i is the index of X, but I'm not sure how to align the index of X to the value in that index of Y.

How can I do this?

CodePudding user response:

Look into np.where, it is exactly what you need:

res = np.where(Y ==  1, np.dot(X, W), np.dot(X, Z))

This assumes that Y can take only value 1 and -1. If that's not the case you can adapt the script above but we need to know what do you expect as result when Y takes a different value.


Also, try to avoid explicit for loops when using numpy, the resulting code will be thousands of times faster.

CodePudding user response:

While it is better to use a no-iteration approach, I think you need a refresher on basic Python iteration.

Make an array:

In [57]: x = np.array(['one','two','three'])

Your style of iteration:

In [58]: for i in x: print(i)
one
two
three

to iterate on indices use range (or arange):

In [59]: for i in range(x.shape[0]): print(i,x[i])
0 one
1 two
2 three

enumerate is a handy way of getting both indices and values:

In [60]: for i,v in enumerate(x): print(i,v)
0 one
1 two
2 three

Your previous question had the same problem (and correction):

How to iterate over a numpy matrix?

  • Related