0

I managed to put the arrays in for loop and, depending on the condition, select the values I need. From these selected values I try to choose the highest value from the matrix a and b. Unfortunately, somehow I miss some syntax.

my code

a=np.array([0, 0, 0, 1, 1, 1, 2, 4,2, 2])
b=np.array([0, 1, 2, 0, 1, 2, 0, 1, 2,5])

max_b=b[0]

for (j), (k) in zip(a,b):
    #print(j,k)
    if j>=2 and k>=1:
        print(j,'a')
        print(k,'b')

output:

4 a
1 b
2 a
2 b
2 a
5 b

i need : From these numbers I need to choose the largest number from j and k

4 a
5 b

I also created the code specifically to get the highest value in the loop from one matrix without other conditions to make it work better, but I can't incorporate it correctly into my code

maxv=a[0]
for i in a:
    
    if i > maxv:
        maxv=i
print(maxv)

This is my attempt, but it is stupid

a=np.array([0, 0, 0, 1, 1, 1, 2, 4,2, 2])
b=np.array([0, 1, 2, 0, 1, 2, 0, 1, 2,5])

#max_b=b[0]

for (j), (k) in zip(a,b):
    #print(j,k)
    if j>=2 and k>=1:
        #print(j,'a')
       # print(k,'b')
        max_a=j
        max_b=k
        if j > max_a:
            max_a=k
        print(max_a)
    

Can you advise me how it could work?

2 Answers2

1

We can use numpy's masking, then .max().

This is a no-for-loops solution, also called vectorization.

import numpy as np

a = np.array([0, 0, 0, 1, 1, 1, 2, 4, 2, 2])
b = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2, 5])

a_gt_2 = a >= 2
b_gt_1 = b >= 1

conditions_apply_mask = a_gt_2 & b_gt_1

a_filtered = a[conditions_apply_mask]
b_filtered = b[conditions_apply_mask]

max_a_filtered = a_filtered.max()
max_b_filtered = b_filtered.max()

print(f"{max_a_filtered}, a")
print(f"{max_b_filtered}, b")

Gulzar
  • 23,452
  • 27
  • 113
  • 201
1

A correct solution using for loops follows.

You were not updating max_b, not keeping max_a at all, and not checking if the current max_b or max_a is smaller than the current value in order to update them.

import numpy as np

a = np.array([0, 0, 0, 1, 1, 1, 2, 4, 2, 2])
b = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2, 5])

max_a = a[0]
max_b = b[0]

for j, k in zip(a, b):
    # print(j,k)
    if j >= 2 and k >= 1:
        if max_a < j :
            max_a = j
        if max_b < k:
            max_b = k

print(f"{max_a}, a)")
print(f"{max_b}, b)")
Gulzar
  • 23,452
  • 27
  • 113
  • 201