ian_chan
ian_chan

Reputation: 355

loop over sorted values of a numpy with repeated values

I have two arrays with the same length:

import numpy as np
a = np.array([1,3,2,2,4])
b = np.array([1,2,3,4,5])
c = np.array([0.1,0.2,0.3,0.6,0.2])

I want to sort a by ascending order, and then add the position of b with the position in c until sum of b is greater than 16. For example, in the first iteration, we will find 1 in a, which is in position 0. Hence b[0] = b[0] + c[0]. Then because np.sum(b) = 15.1 < 16, so the iteration continues.

This is the code I have so far:

 n = 0
 while (np.sum(b) < 16) and (n < len(a)):
     min_a = np.partition(a, n)[n]
     if c[np.where(a==min_a)] < 16 - np.sum(b):
         b[np.where(a==min_a)] = b[np.where(a==min_a)]+c[np.where(a==min_a)]
     n = n + 1

I don't know what I am missing, but the last replacement line does not seem to update the values in b. Also, the code breaks if there are repeated values in a:

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

When there are repeated values, I want to loop them over as other values. In other words, we can either choose a[2] first or a[3] first, since both are 2.

Upvotes: 0

Views: 129

Answers (1)

Rachit Tayal
Rachit Tayal

Reputation: 1292

If I understood correctly, you can try something like this:

import numpy as np
a = np.array([1,3,2,2,4])
b = np.array([1,2,3,4,5])
c = np.array([0.1,0.2,0.3,0.6,0.2])

a1 = np.astype('float')
b1 = np.astype('float')

indexes = np.argsort(a)

for idx in indexes:
  val = a1[idx]          # not sure if this value is used anywhere
  b1[idx] += c[idx]
  if np.sum(b1) > 16:
    break

>>> b1
array([1.1, 2.2, 3.3, 4.6, 5. ])

I think the reason your updates are not reflecting is because you are trying to add floating point values to integer type array objects.

Upvotes: 1

Related Questions