简体   繁体   中英

Stacking 2-d numpy arrays to get a 3-d array in python

I am trying to stack a few 2-D arrays to obtain a 3-D array in python. My motivation behind doing this is to plot the spatial dependence of a variable: var(x,y) where x and y are two different dimensions, for different parameter values param . A minimum reproducible example for the same has been attached below:

while (param<=2):
 var(x,y)= fun  # fun is a function which returns var(x,y) as mentioned above
 param+=1

I want to keep on stacking the 2-D arrays var(x,y) for different values of param, along a 3rd dimension. My output should be of the form:- For param=0: var(x,y), For param=1: var(x,y), For param=2: var(x,y) . Any help regarding the construction of the 3-D array would be highly appreciated. Please note that var(x,y) is a 2-D array.

As suggested by hpaulj, the key idea is to have a list of the 2D arrays and then assemble them into a 3D array. It's usually more efficient to create the array in one go (no appending), so the following should be ideal:

import numpy as np

var_lst = []  # This is where you store the var arrays
while (param<=2):
    var = fun  # fun is a function which returns var(x,y) as mentioned above
    var_lst.append(var)
    param+=1

# Creates a 3D array with the following axes (x, y, param)
var_arr = np.stack(var_lst, 2)

# If later you want different axes, like (param, x, y), you can always swap them around with transpose
var_arr = var_arr.transpose(2, 0, 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM