Argentina
Argentina

Reputation: 1141

Python: Looking for a specific value in array column

I have a specific integer value k and I want to find matching values in a column of a 2d numpy array (using a "for" loop). I thought I could use an if statement and directly compare the single array element with the integer value k. Here is my code:

for i in range(mock.shape[0]):

    n_cl = int(mock[i,0]/3500.)
    zcl = mock[i,5]
    pick = [np.random.random_integers(200, size=(n_cl))]
    print pick[0]   
    if(zcl <= 0.05):

        for k in range(len(pick)) :

            for j in range(z_001.shape[0]):
                n = z_001[j,1]
                if (int(n) == pick[k]):
                    binaries[j,7] = mock[i,0]   
                    binaries[j,8] = mock[i,1]
                    binaries[j,9] = mock[i,2]
                    binaries[j,10] = mock[i,3]
                    binaries[j,11] = mock[i,4]

I always get a ValueError about the truth value of an array with more than one element, which is ambiguous. I understand that the problem is in " int(n) == k", but I wonder where am I wrong, and how could I put things better and make this part of my code work.

Upvotes: 2

Views: 6060

Answers (2)

Argentina
Argentina

Reputation: 1141

I resolved my problem by changing the pick list definition, from pick = [np.random.random_integers(200, size=(n_cl))] to pick = np.random.random_integers(200, size=(n_cl)).

The problem occurred because I had been comparing an array value to an integer value.

Upvotes: 0

felippe
felippe

Reputation: 353

Well, consider:

  1. whenever you are using numpy, you probably don't want to use for loops
  2. The error you get means that you are comparing an numpy array to a single value

So, one possible solution to the problem could be:

import numpy as np

# generating some fake data
x = np.repeat([[1,2,3,4]], 4, axis=0) 
x[2,2] = 200
x[3,1] = 200

# retrieving the indices where "x==200" using np.where
indices = np.where(x==200)
print indices

which gives:

(array([2, 3]), array([2, 1]))

so you can just index any other array (with appropriate shape) with indices and you will get the value of that array in the indices positions.

Upvotes: 3

Related Questions