How to replace each element of an array with a different array in Python?

MWE: Consider the following example.

L0=[[b,0],[b,b]], L1=[[b,b],[b,1]], L2=[[b,b],[2,b]]

S=[[0,1,2],[2,0,1]] 

Is there any way to replace each element S with L0 for 0 and L1 for 1 and L2 for 2 in S to get S1, as in the image? enter image description here

In fact, I want the python program to check: if the element S is zero, then it will replace 0 with a predefined 2D array, etc.

+4
source share
2 answers

Yes. First we can build a numpy array containing L0, L1and L2:

A = np.array([L0, L1, L2])

Next we create a numpy array S:

B = np.array(S)

now we have for C = A[B](or C = np.take(A,B,axis=0)as suggested by @Divakar):

>>> C = np.take(A,B,axis=0)
>>> C
array([[[[b, 0],
         [b, b]],

        [[b, b],
         [b, 1]],

        [[b, b],
         [2, b]]],


       [[[b, b],
         [2, b]],

        [[b, 0],
         [b, b]],

        [[b, b],
         [b, 1]]]])

, , , : 2D-. , ( swapaxes, @PaulPanzer), , :

>>> C.transpose(0,2,1,3).reshape(4,6)
array([[b, 0, b, b, b, b],
       [b, b, b, 1, 2, b],
       [b, b, b, 0, b, b],
       [2, b, b, b, b, 1]])

4 6, , L0, L1, L2 S, :

A = np.array([L0, L1, L2])
B = np.array(S)
m, n = B.shape
_, u, v = A.shape
np.take(A,B,axis=0).swapaxes(1,2).reshape(u*m, v*n)

@DSM, Numpy-1.13 np.block , :

>>> np.block([[A[i] for i in row] for row in S])
array([[b, 0, b, b, b, b],
       [b, b, b, 1, 2, b],
       [b, b, b, 0, b, b],
       [2, b, b, b, b, 1]])
+5

Li , Kronecker np.kron:

import numpy as np

L0=[[b,0],[b,b]]; L1=[[b,b],[b,1]]; L2=[[b,b],[2,b]]

S=[[0,1,2],[2,0,1]] 

S1 = sum(np.kron(np.equal(i, S), L) for i, L in enumerate((L0, L1, L2)))

S1, b = 3:

[[3 0 3 3 3 3]
 [3 3 3 1 2 3]
 [3 3 3 0 3 3]
 [2 3 3 3 3 1]]
+1

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


All Articles