1
p= np.array([[ 1,  2,  3,  4,  5],
   [ 6,  7,  8,  9, 10],
   [11, 12, 13, 14, 15],
   [16, 17, 18, 19, 20]])

I have the above array and need to find the items that are divisible by 2 and 3 without converting it to a flat array using for-loops and then slicing/masking.

I was able to figure out the for-loops part and am running into some issues with the slicing/masking part.

# we know that 6, 12 and 18 are divisible by 2 and 3
# therefore we can use slicing to pull those numbers out of the array

print(p[1:2,0:1]) # slice array to return 6
print(p[2:3,1:2]) # slice array to return 12
print(p[3:4,2:3]) # slice array to return 18

m=np.ma.masked_where(((p[:, :]%2==0)&(p[:, :]%3==0)),p)
print(m)

mask=np.logical_and(p%2==0,p%3==0)
print(mask)

Is there a more efficient way of slicing the array to find 6, 12 and 18? Also, is there a way to make either of the two mask functions output just 6, 12, and 18? The first one shows the inverse of what I want while the other returns a Boolean answer.

1
  • Refer here Commented Jan 29, 2021 at 21:14

2 Answers 2

1

You nearly had it!

mask=np.logical_and(p%2==0,p%3==0)

gives you True where p % 2 == 0 and p % 3 == 0.

mask = array([[False, False, False, False, False],
       [ True, False, False, False, False],
       [False,  True, False, False, False],
       [False, False,  True, False, False]])

From this, you can get the values of p where mask is True by simply

p[mask]

Which gives the output:

array([ 6, 12, 18])
Sign up to request clarification or add additional context in comments.

2 Comments

Whoa thanks Pranav. I have tried alot of different things to do that but apparently not that one. I appreciate the help.
If this provided your preferred answer to your question, please consider accepting it.
1

Why not simply do p[p%6==0] ?

import numpy as np

p= np.array([[ 1,  2,  3,  4,  5],
   [ 6,  7,  8,  9, 10],
   [11, 12, 13, 14, 15],
   [16, 17, 18, 19, 20]])

p[p%6==0] # [ 6 12 18]

2 Comments

Good question but the assignment says 3 and 2. But I think this would be acceptable. :D
I hope it is. Leveraging basic math should be encouraged as it always gives better/faster algorithms.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.