Use dstack:

>>> np.dstack((A, B)).shape
(480, 640, 4)

This handles the cases where the arrays have different numbers of dimensions and stacks the arrays along the third axis.

Otherwise, to use append or concatenate, you'll have to make B three dimensional yourself and specify the axis you want to join them on:

>>> np.append(A, np.atleast_3d(B), axis=2).shape
(480, 640, 4)
Answer from Alex Riley on Stack Overflow
Discussions

How to add elements to 3 dimensional array in python - Stack Overflow
Why don't you want to use numpy, by the way? 2013-03-16T11:38:27.987Z+00:00 ... i can use that. but how can i initialize not as fixed array. i mean i dont know my array size at first. 2013-03-16T11:43:10.443Z+00:00 ... In cases like that, I usually append all elements to a one-dimensional, ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
January 30, 2018
python - Creating a 3d numpy array matrix using append method - Stack Overflow
Is there a way to create a 3d numpy array by appending 2d numpy arrays? What I currently do is append my 2d numpy array into an initialized list of pre determined 2d numpy array, i.e., List=[np.zer... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - numpy: Append row to a individual 3D array - Stack Overflow
There's numerous posts and blogs talking about how to manipulate 2D arrays using append, vstack or concatenate, but I couldn't make it work in 3D. Problem Assumptions: --The 3D array will have the More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Append Value to 3D array numpy - Stack Overflow
I iterate over a 3D numpy array and want to append in every step a float value to the array in the 3rd dimension (axis =2). Something like (I know the code doesn't work as of now, latIndex, data and More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 18, 2019
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ generated โ€บ numpy.append.html
numpy.append โ€” NumPy v2.5 Manual
A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python โ€บ numpy
NumPy: append() to add values to an array | note.nkmk.me
February 4, 2024 - a_3d_ex = np.arange(12).reshape(2, 3, 2) * 10 print(a_3d_ex) # [[[ 0 10] # [ 20 30] # [ 40 50]] # # [[ 60 70] # [ 80 90] # [100 110]]] print(a_3d_ex.shape) # (2, 3, 2) print(np.append(a_3d, a_3d_ex, axis=0)) # [[[ 0 1] # [ 2 3] # [ 4 5]] # # [[ 6 7] # [ 8 9] # [ 10 11]] # # [[ 0 10] # [ 20 30] # [ 40 50]] # # [[ 60 70] # [ 80 90] # [100 110]]] print(np.append(a_3d, a_3d_ex, axis=0).shape) # (4, 3, 2) print(np.append(a_3d, a_3d_ex, axis=1)) # [[[ 0 1] # [ 2 3] # [ 4 5] # [ 0 10] # [ 20 30] # [ 40 50]] # # [[ 6 7] # [ 8 9] # [ 10 11] # [ 60 70] # [ 80 90] # [100 110]]] print(np.append(a_3d, a_3d
Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 28246025 โ€บ numpy-append-row-to-a-individual-3d-array
python - numpy: Append row to a individual 3D array - Stack Overflow
There's numerous posts and blogs talking about how to manipulate 2D arrays using append, vstack or concatenate, but I couldn't make it work in 3D. Problem Assumptions: --The 3D array will have the shape (k, m, 2). --k will be a known value ยท --m could range from 1 to n and is not predetermined ยท In [1]: import numpy as np In [2]: a = np.empty((3, 1, 2)) Out[2]: array([[[0., 0.]], [[0., 0.]], [[0., 0.]]]) In [3]: a[0] = [[5, 6]] In [4]: a Out[4]: array([[[5., 6.]], [[0., 0.]], [[0., 0.]]]) In [5]: a[0] = np.vstack((a[0], [[10, 15]])) Out[5]: ValueError: could not broadcast input array from shape (2,2) into shape(1,2) In [6]: a[0] = np.append(a[0], [[10, 15]], axis=0) Out[6]: ValueError: could not broadcast input array from shape (2,2) into shape(1,2) The desired output would be.
Top answer
1 of 1
2

You can allocate extra space for your array grid_data, fill it with the NaN, and keep track of the next index to be filled in another array while iterating through and filling with values from data. If you completely fill the third dimension for some lat_idx, lon_idx with non-NaN values, then you just allocate more space. Since appending is expensive with numpy, it's best that this extra space is pretty large so you only do it once or twice (below I allocate twice the original space).

Once the array is filled, you can remove the added space that was unused with numpy.isnan(). This solution does what you want but is very slow (for the example values you gave it took about two minutes), but the slow execution comes from iterating rather than the numpy operations.

Here's the code:

import random
import numpy as np

grid_data = np.ones(shape=(121, 201, 1000))
data = np.random.rand(4800, 4800)

# keep track of next index to fill for all the arrays in axis 2
next_to_fill = np.full(shape=(grid_data.shape[0], grid_data.shape[1]),
                       fill_value=grid_data.shape[2],
                       dtype=np.int32)

# allocate more space
double_shape = (grid_data.shape[0], grid_data.shape[1], grid_data.shape[2] * 2)
extra_space = np.full(shape=double_shape, fill_value=np.nan)
grid_data = np.append(grid_data, extra_space, axis=2)

for row in range(4800):
    for col in range(4800):
        lat_idx = random.randint(0, 120)
        lon_idx = random.randint(0, 200)

        # allocate more space if needed
        if next_to_fill[lat_idx, lon_idx] >= grid_data.shape[2]:
            grid_data = np.append(grid_data, extra_space, axis=2)

        grid_data[lat_idx, lon_idx, next_to_fill[lat_idx, lon_idx]] = data[row,
                                                                           col]
        next_to_fill[lat_idx, lon_idx] += 1

# remove unnecessary nans that were appended
not_all_nan_idxs = ~np.isnan(grid_data).all(axis=(0, 1))
grid_data = grid_data[:, :, not_all_nan_idxs]
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 1.13 โ€บ reference โ€บ generated โ€บ numpy.dstack.html
numpy.dstack โ€” NumPy v1.13 Manual
June 10, 2017 - Equivalent to np.concatenate(tup, axis=2) if tup contains arrays that are at least 3-dimensional.
๐ŸŒ
Linux Hint
linuxhint.com โ€บ numpy-array-append
Linux Hint โ€“ Linux Hint
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ numpy โ€บ numpy_append.htm
Numpy Append() Method
The Numpy Append() method adds values to the end of an input array, allocating a new array for the result rather than modifying the original in place. If no axis is specified then both the array and values are flattened before appending.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ numpy-append-in-python
numpy.append() in Python | DigitalOcean
Technical tutorials, Q&A, events โ€” This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
๐ŸŒ
SciPy
docs.scipy.org โ€บ doc โ€บ โ€บ numpy-1.13.0 โ€บ reference โ€บ generated โ€บ numpy.dstack.html
numpy.dstack โ€” NumPy v1.13 Manual
June 10, 2017 - Rebuilds arrays divided by dsplit. This is a simple way to stack 2D arrays (images) into a single 3D array for processing. This function continues to be supported for backward compatibility, but you should prefer np.concatenate or np.stack. The np.stack function was added in NumPy 1.10.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 70723533 โ€บ numpy-how-to-append-2d-array-to-the-end-of-3d-array
python - Numpy: How to append 2d array to the end of 3d array? - Stack Overflow
January 15, 2022 - I try this: Append 2D array to 3D array, extending third dimension, but I want my original A array grow up not to make new array. ... I checked it. It can't broadcast results to the original array the way I want ... In numpy you can't 'grow up' an array. You can only make a new array with values copied from the originals.