Home > Enterprise >  How put one array into another array on specific place using numpy?
How put one array into another array on specific place using numpy?

Time:12-15

I have a small question.

e.g. I have

a = [[1],[2],[3],[4],[5]]
b = numpy.zeros((8, 1))

I want to get

c = [[0],[0],[1],[2],[3],[0],[4],[5]]

I know, that in array c the rows 0,1 and -3 remain = 0

Other option, how can I add a zero rows on specific place, namely rows 0,1 and -3

many thanks in advance!

CodePudding user response:

For a general approach, you can try the following:

a = [[1],[2],[3],[4],[5]]
b = np.zeros((8, 1))
index = [0, 1, -3]
# convert negative index to positive index : -3 to 5
zero_indexes = np.asarray(index) % b.shape[0]
# [0, 1, -3] -> array([0, 1, 5])
all_indexes = np.arange(b.shape[0])
zero = np.isin(all_indexes, zero_indexes)
# insert 'a' to not_zero index
b[~zero] = a
print(b)

You can use np.insert.

a = [[1],[2],[3],[4],[5]]
# ---^0--^1--^2--^3--^4
# two times insert in index : 0
# one time insert in index : 3
b = np.insert(np.asarray(a), (0, 0, 3), values=[0], axis=0)
print(b)

Output:

[[0]
 [0]
 [1]
 [2]
 [3]
 [0]
 [4]
 [5]]

CodePudding user response:

You can specify the indices you want to assign in b, then assign the values from a to those indices.

import numpy

a = [[1],[2],[3],[4],[5]]
b = numpy.zeros((8, 1))

# you can use your own method of determining the indices to overwrite.
# this example uses the indices specified in your question.
b_indices = [2,3,4,6,7] # indices in b to overwrite, len(b_indices) == len(a)

b[b_indices] = numpy.array(a) # overwrite specified indices in b with values from a

output:

array([[0.],
   [0.],
   [1.],
   [2.],
   [3.],
   [0.],
   [4.],
   [5.]])
  • Related