简体   繁体   中英

Get Item Index and row Index of Matrices in a list to a matrix

I am pretty new to Python and am trying to tackle the following problem:

I have a list, for example: (items in list are either empty or arrays of dimension nx 2):

a = np.array([])
b = np.array([1,2])
c = np.array([[5,6],[7,8]])
d = np.array([[11,12],[13,14],[15,16]])

D1 = [a,b,c,d]

I am then removing the empty members of the list like this:

D2 = [i for i in D1 if len(i) > 0]

to be able to stack the remaining items of the list in one 2D Array like this:

E = np.vstack(D2)

which gives me:

E = [[ 1  2]
     [ 5  6]
     [ 7  8]
     [11 12]
     [13 14]
     [15 16]]

Now, what I am trying to get is a matrix looking like this:

out = [[1 0]
       [2 0]
       [2 1]
       [3 0]
       [3 1]
       [3 2]]

Explanation:

The first column of out corresponds to the List Index of the corresponding row of E from D1 (List with empty entry!). The second column of out corresponds to the Row Index of the corresponding row of E from D1.

Example:

The 3rd row of out[2,:] = [2 1] means: The 3rd row of E originates D1 at List Index 2 and Row Index 1 of the matrix in D1.

I am happy to make it more clear if needed. Any help is appreciated.

I think you don't need to define D2 and E, you can work with D1 only. then for every item in D1 you need to store the index of the item and the indices of the elements of that item in an array. after you need to filter this array and get rid of the empty elements. The last step is to stack the remaining elements of the array. And you're done! The last thing in the b NumPy array you forget to put the elements within another array like you did in c and d.

import numpy as np
a = np.array([])
b = np.array([[1,2]])
c = np.array([[5,6],[7,8]])
d = np.array([[11,12],[13,14],[15,16]])
D1 = [a,b,c,d]
M = [ [[i,j] for j in range(len(D1[i])) ]for i in range(len(D1)) ]
M = [ x for x in M if len(x)> 0 ]
M = np.vstack(M)
print(M)

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