Search code examples
python-2.7numpyindexingindices

Access indices from 2D list - Python


I'm trying to access a list of indices from a 2D list with the following error. Basically I want to find where my data is between two values, and set a 'weights' array to 1.0 to use for a later calculation.

#data = numpy array of size (141,141)
weights = np.zeros([141,141])
ind = [x for x,y in enumerate(data) if y>40. and y<50.]
weights[ind] = 1.0

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I've tried using np.extract() but that doesn't give indices...


Solution

  • Think I got it to work doing this:

    #data = numpy array of size (141,141)
    weights = np.zeros([141,141])
    ind = ((data > 40.) & (data < 50.)).astype(float) 
    weights[np.where(ind==1)]=1.0
    

    thanks to the helpful comment about using numpy's vectorizing capability. The third line outputs an array of size (141,141) of 1's where the conditions are met, and 0's where it fails. Then I filled my 'weights' array with 1.0s at those locations.