Stripers247
Stripers247

Reputation: 2335

Break out of loop if data in one array exceedes some VALUE in another Python

I have two arrays, id, and x where id is a unique identifier that tells us that the values in x belong to a specific group. What I want to do is go through the values in x to see if some condition is meet and if so print the corresponding x value. For example

id = np.array([1,1,1,2,2,2,3,3,3,4,4,4,5,5,5])
x = np.array([10,9,6,9,7,1,12,5,10,9,8,4,6,2,1])


  counter = 1
  for i in range(len(id)):
    if id[i] == counter:
        for j in range(i,len(id)):   
           if x[j] > 7:
             continue 
           else:
              print(id[i],x[j])  
              counter += 1    
              break

prints

1 6
2 7
3 5
4 4
5 6

Now if we instead have

id = np.array([1,1,1,2,2,2,3,3,3,4,4,4,5,5,5])
x = np.array([10,9,6,9,7,1,12,11,10,9,8,4,6,2,1])

The output is

1 6
2 7
3 4
4 4
5 6

Which is not the output I want because 4 is not in the group that has an id value of 3. So my question is how does one only have the condition if x[j] > 7: evaluated if the x values correspond to an id vale that represents it and not skip over that group?

Upvotes: 0

Views: 72

Answers (1)

user1269942
user1269942

Reputation: 3852

I'm a bit confused but I'll take a stab... could a dictionary help?

id = np.array([1,1,1,2,2,2,3,3,3,4,4,4,5,5,5])
x = np.array([10,9,6,9,7,1,12,5,10,9,8,4,6,2,1])

dict = {}
for i in range(len(id)):
    if id[i] not in dict:
        dict[id[i]] = []
    dict[id[i]].append(x[i])

#you now have a dict that is keyed by your group-id and has a list of values for that group.

for group in dict:
    vals_in_group = dict[group]
    for val in vals_in_group:
        #check value? or just print
        print group, val

Upvotes: 3

Related Questions