Home > OS >  How to iterate over a numpy matrix?
How to iterate over a numpy matrix?

Time:09-27

I have an matrix

              X = [[0. 0. 0. ... 0. 0. 0.]
                  [0. 0. 0. ... 0. 0. 0.]
                  [0. 0. 0. ... 0. 0. 0.]
                   ...
                  [0. 0. 0. ... 0. 0. 0.]]

and I want to iterate over the rows.

My goal is to implement the below for loop:

loglike = []
for i in X_test:
    p = np.sum(np.multiply(X[i], np.log(posprob))   np.multiply((1-X[i]), np.log(1-posprob)))
    loglike.append(p)
print(loglike)

but I receive the error IndexError: arrays used as indices must be of integer (or boolean) type.

Even when I try to do a simple for loop print statement I receive the same error.

for i in X:
     print(X[i])

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

I see other people have asked other people have asked this question, but the answer seem to be exactly what I have. Any ideas on where I'm going wrong?

CodePudding user response:

As a addition to @Eshwar S R's answer, this calculation can be done without a loop.

Is the output of the following code what you want?

loglike = np.sum(np.multiply(X_test, np.log(posprob))   np.multiply((1-X_test), np.log(1-posprob)), axis=1)

CodePudding user response:

i is already a numpy array. No need to index it again as X[i]. Try this:

loglike = []
for i in X_test:
    p = np.sum(np.multiply(i, np.log(posprob))   np.multiply((1-i), np.log(1-posprob)))
    loglike.append(p)
print(loglike)
  • Related