Danny Maksoud
Danny Maksoud

Reputation: 23

Comparing another array with a list full of arrays

So I've essentially split an array#1(full of float values) into 100 arrays contained in a list, and what I want to do is compare it to an array#2(also full of floats) and have the program give me the number of values in array#2 that fall within the range of each of the 100 arrays in the list.

I may not have explained it well enough, but I've done this successfully for the first two arrays however I can't find a way to do it elegantly through a 'for' loop so I don't have to type it out 100 times.

Here's the code:

manual_bins_threshim = np.array_split(threshim_by_size, 100)

def count(rand, l, r):      
   return len(list(i for i in rand if l <= i <= r))

a = np.array(manual_bins_threshim[0:1])
l = a[:][0][0]
r = a[:][0][len(a[:][0]) -1]
a_1 = count(array2, l, r)

b = np.array(manual_bins_threshim[1:2])
l = b[:][0][0]
r = b[:][0][len(b[:][0]) -1]
b_1 = count(array2, l, r)

print(a_1,b_1)

I'm also open to a function that can do this in a different way if I've made it way more complicated than it needs to be.

Upvotes: 0

Views: 283

Answers (2)

Grandesty
Grandesty

Reputation: 86

This question requires some numpy high dimension array operation:

import numpy as np

threshim_by_size = np.random.rand(300)
manual_bins_threshim = np.array_split(threshim_by_size, 100)
array2 = np.random.rand(20)


def count(rand, ll, rr):
    return len(list(i for i in rand if ll <= i <= rr))


a = np.array(manual_bins_threshim[0:1])
l = a[:][0][0]
r = a[:][0][len(a[:][0]) - 1]
a_1 = count(array2, l, r)

b = np.array(manual_bins_threshim[1:2])
l = b[:][0][0]
r = b[:][0][len(b[:][0]) - 1]
b_1 = count(array2, l, r)

print(a_1, b_1)


def array_op():
    reshaped_threshim_by_size = np.reshape(threshim_by_size, [100, -1])
    ll = reshaped_threshim_by_size[:, 0:1]
    rr = reshaped_threshim_by_size[:, -1:]
    reshape_array2 = np.reshape(array2, [1, -1])
    mask = np.logical_and(ll <= reshape_array2, reshape_array2 <= rr)
    return np.sum(mask, axis=1)


res = array_op()
assert res[0] == a_1 and res[1] == b_1

Upvotes: 1

ski
ski

Reputation: 21

Just iterate over the elements of manual_bins_threshim :

for a in manual_bins_threshim:
    l = a[0,0]
    r = a[0,-1]
    print(count(array2, l, r))

A few words about my modifications:
l = a[:][0][0]l = a[0,0] - I don't think [:] is needed here (it creates a new array referring to the same data).
r = a[:][0][len(a[:][0]) -1]r = a[0,-1] - the last element of an array (or a list) can be accessed with -1 (by the way, the n-th element from the end can be accessed with -n).

Upvotes: 1

Related Questions