0

How can I efficiently append values to a multidimensional numpy array?

import numpy as np

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

I want to append np.NaN for k=2 times to each dimension/array of the outer array?

One option would be to use a loop - but I guess there must be something smarter (vectorized) in numpy

Expected result would be:

np.array([[1,2,3, np.NaN, np.NaN, ], [4,5,6, np.NaN, np.NaN, ]])

I.e. I am looking for a way to:

np.concatenate((a, np.NaN))

on all the inner dimensions.

A

np.append(a,  [[np.NaN, np.NaN]], axis=0)

fails with:

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 3 and the array at index 1 has size 2
1
  • With axis np.append is just a call to np.concatenate, as indicated by the traceback. You are trying to join a (2,3) and (1,2) on the first dimension. But the target is a (2,5), so you need to add a (2,2) on axis 1. Commented Mar 14, 2021 at 16:01

1 Answer 1

2

For your problem np.hstack() or np.pad() should do the job.

Using np.hstack():

k = 2
a_mat = np.array([[1,2,3], [4, 5, 6]])
nan_mat = np.zeros((a_mat.shape[0], k))
nan_mat.fill(np.nan)

a_mat = np.hstack((a_mat, nan_mat))

Using np.pad():

k = 2
padding_shape = [(0, 0), (0, k)]   # [(dim1_before_pads, dim1_after_pads)..]
a_mat = np.array([[1,2,3], [4, 5, 6]])
np.pad(a_mat, mode='constant', constant_values=np.nan)

Note: Incase you are using np.pad() for filling with np.nan, check this post out as well: about padding with np.nan

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.