Home > other >  Integrate element of an array into another array
Integrate element of an array into another array

Time:10-01

I have one dimensional numpy array which looks like this:

 ['0000' '0001' '0010' '0011' '0100' '0101' '0110' '0111' '1000' '1001'
 '1010' '1011' '1100' '1101' '1110' '1111']

I am trying to insert selected element from this array into another array, which would look like this:

 [[0 1]
 [1 0]
 [0 1]
 [0 1]]

The final results should be as follow:

 [[0 0 1]
 [0 1 0]
 [0 0 1]
 [0 0 1]]

in case we insert the first element of the first array into position 0 of the second array.

I am trying to do it with numpyp.column_stack but it doesn`t work as the first array is actually an 1D array of strings, while the second is a 2D array of integers. I do not know whot to tranform it and how to proceed.

CodePudding user response:

The easiest thing is probably to convert your list of strings to a two-dimensional numpy array of integers. Then you can use column_stack at will:

import numpy as np

l = ['0000','0001','0010']

l = np.array([list(s) for s in l]).astype(int)

a = np.array([
     [0, 1],
     [1, 0],
     [0, 1],
     [0, 1],
 ])

np.column_stack((l[0], a))

Giving you:

array([[0, 0, 1],
       [0, 1, 0],
       [0, 0, 1],
       [0, 0, 1]])

You could also do the conversion later depending on your needs, though if you are doing this a lot, it's probably easier to work with two numpy arrays of the same type:

l = ['0000','0001','0010']
np.column_stack((list(l[0]), a)).astype(int)
  • Related