edub
edub

Reputation: 689

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...

Upvotes: 0

Views: 84

Answers (2)

HYRY
HYRY

Reputation: 97261

If you need to fill weights with ( (value - 40) / 10), then Use numpy.ma is better:

data = np.random.uniform(0, 100, size=(141, 141))
weights = ((np.ma.masked_outside(data, 40, 50) - 40) / 10).filled(0)

Upvotes: 1

edub
edub

Reputation: 689

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.

Upvotes: 1

Related Questions