1

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!

1
  • What's the logic for where the 0 should be in c? Commented Dec 14, 2022 at 18:09

2 Answers 2

1

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]]
Sign up to request clarification or add additional context in comments.

Comments

1

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.]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.