0

I'm looking for a way to efficiently add a fixed number of np.nan values at the beginning of each array in a numpy array of shape (3,123...):

Original numpy array:

[[1,2,3...],
 [4,5,6...],
 [7,8,9...]]

New numpy array:

[[nan,nan,1,2,3...],
 [nan,nan,4,5,6...],
 [nan,nan,7,8,9...]]

I tried with a for loop:

import numpy as np

original_array = np.random.rand(3,3)
gap = np.empty(shape=(2,))
gap.fill(np.nan)
new_array = np.zeros(shape=(3,5))
for i,row in enumerate(original_array):
    new_array[i] = np.concatenate([gap,row])

It works but this is probably not the best way to do it.

1
  • Look at np.hstack Commented Feb 7, 2023 at 15:23

2 Answers 2

2

You could also use np.pad

import numpy as np

original_array = np.arange(1, 10).reshape(-1, 3).astype(np.float32)
npad = ((0, 0), (2, 0))
np.pad(original_array,npad,mode='constant',constant_values=(np.nan))

Output:

array([[nan, nan,  1.,  2.,  3.],
       [nan, nan,  4.,  5.,  6.],
       [nan, nan,  7.,  8.,  9.]], dtype=float32)
Sign up to request clarification or add additional context in comments.

Comments

0

A possible solution (thanks to @roganjosh for suggesting the use of numpy.full), which is based on numpy.hstack:

a = np.full((3,2), np.nan)
b = np.arange(1, 10).reshape(-1, 3)
np.hstack((a, b))    

Output:

array([[nan, nan,  1.,  2.,  3.],
       [nan, nan,  4.,  5.,  6.],
       [nan, nan,  7.,  8.,  9.]])

1 Comment

Thanks a lot, @roganjosh! np.full is much better and I have edited my solution accordingly.

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.