简体   繁体   中英

Save rows of a bidimensional numpy array in another array

I have a bidimensional np array V (100000x50). I want to create a new array V_tgt in which I keep just certain rows of V, so the dimension will be (ix50). It may be easy to do it but I tried different things and it seems to save just the first of the 50 elements. My code is the following:

V_tgt = np.array([])
for i in IX_items:
    if i in IX_tgt_items:
        V_tgt=np.append(V_tgt, V[i])

I tried with functions such as insert and delete as well but it didn't work.How can I save all the values and create an array with the right dimension? Any help is really appreciated.

From your comments I assume that you have some kind of list of target indices (in my example tgt_idx1 and tgt_idx2 )that tells you which elements to take from V. You could do something like this:

import numpy as np

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


mask = []
for i, elem in enumerate(V):
    inTargets = i in tgt_idx1 and i in tgt_idx2
    mask.append(inTargets)
print mask

V_tgt = V[mask]
print V_tgt

This prints

[False, True, False, True]
[[ 4  5  6]
 [10 11 12]]

Let's first simplify the problem. With an initial array ( a ):

a = np.array([45, 29, 76, 23, 76, 98, 21, 63])

and the index arrays :

i1 = np.array([1, 3, 5, 7, 9])
i2 = np.array([0, 1, 2, 3, 4])

then we can use a simple list comprehension to get the elements from a that are at indexes in both i1 and i2 :

np.array([e for i, e in enumerate(a) if i in i1 and i in i2])

which is very readable and outputs:

array([29, 23])

I am sure you can adapt this to the variables you have given to your arrays .

The performance of np.append is probably killing this, why not create a new overlap of your two indices, then subset:

#using @Joe Iddons data
a = np.array([45, 29, 76, 23, 76, 98, 21, 63])
i1 = np.array([1, 3, 5, 7, 9])
i2 = np.array([0, 1, 2, 3, 4])

Then find the intersect of i1 and i2:

indices = np.intersect1d(i1,i2)

and subset:

a[indices]
array([29, 23])

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