3

I have a numpy array of numpy arrays and I need to add a leading zero to each of the inner arrays:

a = [[1 2] [3 4] [5 6]] --> b = [[0 1 2] [0 3 4] [0 5 6]]

Looping through like this:

for item in a:

item = np.insert(item, 0, 0)

doesn't help.

Numpy.put() flattens the array, which I don't want.

Any suggestions how I accomplish this? Thanks

3
  • You can also use np.hstack, but np.insert answered below is more effectient Commented Nov 1, 2024 at 1:20
  • This question is similar to: Numpy add (append) value to each row of 2-d array. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Nov 1, 2024 at 1:22
  • I'm not sure how good that dupe target is, but I wanted to throw it out there. Commented Nov 1, 2024 at 1:22

1 Answer 1

4

np.insert - insert values along the given axis before the given indices. If axis is None then array is flattened first.

import numpy as np

a = np.array([[1, 2], [3, 4], [5, 6]])
b = np.insert(a, 0, 0, axis=1)
print(b)

Result:

[[0 1 2]
 [0 3 4]
 [0 5 6]]
Sign up to request clarification or add additional context in comments.

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.