Comparing each element of two arrays

时间:2019-01-18 18:37:39

标签: python arrays

So I have two arrays and i want the amount of elements smaller than the individual elements of the other arrays. So i have two arrays like this:

array1 = np.array([4.20, 3.52, 9.44, 12.00, 10.50, 7.30, 9.44])
array2 = np.array([3.8600000000000003, 5.75, 8.37, 9.969999999999999, 11.25]

And then in the output i want an array where the first element in the array is the amount of elements in array1 smaller than the first element in array2. And then the second element in the output is the amount of elements in array1 smaller than the second element in array2. So I want the following output:

output = [1, 2, 3, 5, 6]

I hope this makes sense. I have tried to make two for loops where i appends the number as such:

for i in range(len(array1)):
    for j in range(len(array2)):
        if GPA[i] < thres[j]:
        number1 += 1
    else:
        number1 = 0
failed.append(number1)

But it just gives an output that makes no sense.

1 个答案:

答案 0 :(得分:0)

You can iterate over each element in the second array, and use that element to create a mask, then sum up all of the True values:

output = []
for el in array2:
    output.append(np.sum(array1 < el))

Output:

[1, 2, 3, 5, 6]

Your approach is almost correct. I cleaned it up a bit. You can iterate over the elements themselves instead of their indexes.

failed = []
for el2 in array2:
    number1 = 0
    for el1 in array1:
        if el1 < el2:
            number1 += 1
    failed.append(number1)

Output:

[1, 2, 3, 5, 6]

I would still use the first answer though as it should be a bit quicker.