Create a new numpy array based on the conditions set in the numpy array

How to create an array based on certain conditions in another array. For example, if I have an array that gives me a base number, a start and end number, and then a few other base numbers. I want to create a new matrix that lists the base number, the loop number (based on the start / end), and then another base number associated with this, ignoring 0. I am trying to find a way to do this without using the for loop.

For example, how can I get array B from array A.

           Base Start End Base1 Base2 Base3
A=np.array([[100,  1,   2,  101,  102,  103],
            [101,  3,   4,  100,  103,    0]])


B=np.array[[100,1,101,1],
           [100,1,102,1],
           [100,1,103,1],
           [100,2,101,2],
           [100,2,102,2],
           [100,2,103,2],
           [101,3,100,3],
           [101,3,103,3],
           [101,4,100,4],
           [101,4,103,4]]

Thanks for the help!

+4
source share
2 answers

Here you go ... nasty list comprehension

A = array([[100,   1,   2, 101, 102, 103], [101,   3,   4, 100, 103,   0]])
B = [[A[i,0], b, c, b] for i in range(len(A)) for b in A[i,1:3] for c in A[i,3:6] if c != 0]

>>> B
[[100, 1, 101, 1],
 [100, 1, 102, 1],
 [100, 1, 103, 1],
 [100, 2, 101, 2],
 [100, 2, 102, 2],
 [100, 2, 103, 2],
 [101, 3, 100, 3],
 [101, 3, 103, 3],
 [101, 4, 100, 4],
 [101, 4, 103, 4]]
+2

: numpy, no python

C = np.empty((len(A), 2,3,4), np.int)
C[...,0] = A[:,0  ][:,None,None]
C[...,1] = A[:,1:3][:,:   ,None]
C[...,2] = A[:,3: ][:,None,:   ]
C[...,3] = np.arange(len(A)*2).reshape(len(A),2,1)+1

C = C.reshape(-1,4)
C = C[C[:,2]!=0]

print C

:

edit2: (. ):

C = np.empty((len(A), 2,3,2,2), np.int)
C[...,0,0] = A[:,0  ][:,None,None]
C[...,1,0] = A[:,3: ][:,None,:   ]
C[...,:,1] = A[:,1:3][:,:   ,None,None]
+2

Source: https://habr.com/ru/post/1529887/


All Articles