简体   繁体   中英

How to “extract” certain values out of an array?

Say i have an array of numbers:

a1 = np.arange(1,(30)+1)[:,None]        # or some other way og making (n,1) array

and I want to take every 4th nr out and name it something else, I'll do like this:

a2 = aaa[0:30:2]

Thats fine, but how do I take out all numbers except those above?? In other words:

   [[2.]
    [3.]
    [5.]
    [6.]
    [8.]
    [9.]....

I have no idea how to do that!

Create a boolean mask and apply it on your array:

>>> a2 = np.ones_like(a1)
>>> a2[::3] = 0
>>> a1[a2.astype(bool)]
array([ 2,  3,  5,  6,  8,  9, 11, 12, 14, 15, 17, 18, 20, 21, 23, 24, 26,
       27, 29, 30])

If you want to extract the other elements, just apply the inverse boolean mask:

>>> a1[~a2.astype(bool)]
array([ 1,  4,  7, 10, 13, 16, 19, 22, 25, 28])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM