I have this vector
v = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20)
I want to remove the multiples of 2 and 3. How would I do this?
I tried to do this but I doesn't work:
import numpy as np
V = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20)
Mul3 = np.arange(1,21,3)
Mul2 = np.arange(1,21,2)
V1 = V [-mul2]
V2 = V1 [-mul3]
Given that you use NumPy already you can use boolean array indexing to remove the multiples of 2
and 3
:
>>> import numpy as np
>>> v = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20) # that's a tuple
>>> arr = np.array(v) # convert the tuple to a numpy array
>>> arr[(arr % 2 != 0) & (arr % 3 != 0)]
array([ 1, 5, 7, 11, 13, 19])
The (arr % 2 != 0)
creates a boolean mask where multiples of 2
are False
and everything else True
and likewise the (arr % 3 != 0)
works for multiples of 3
. These two masks are combined using &
(and) and then used as mask for your arr
I assume by vector
you refer to the tuple you set up with the ()
.
You can use a list comprehension with two conditions, using the modulo
oprerator you can read up on here:
res = [i for i in v if not any([i % 2 == 0, i % 3 == 0])]
Returns
[1, 5, 7, 11, 13, 19]
This returns a standard Python list; if you want np arrays or sth, just update your question.
You could use the outcome of the modulos 2 and 3 directly for filtering in a list comprehension. This keeps items whose mod 2
and mod 3
values gives a number other than a falsy 0:
>>> [i for i in v if i%2 and i%3]
[1, 5, 7, 11, 13, 19]
You can make it more verbose if the above is not intuitive enough by making the conditionals explicitly test for non zero outcomes:
>>> [i for i in v if not i%2==0 and not i%3==0]
[1, 5, 7, 11, 13, 19]