Home > Enterprise >  how do I initialize a 3D array with two 2D array in python?
how do I initialize a 3D array with two 2D array in python?

Time:11-29

I have two array as follows:

a=np.vstack([np.loadtxt(path, dtype='float') for path in glob.iglob(r'E:/PostDoc/720/*.txt')])
b=np.vstack([np.loadtxt(path, dtype='float') for path in glob.iglob(r'E:/PostDoc/1080/*.txt')])

the a and b are two arrays with size (640,6) now I define a 3D array as follows:

c = [[[0 for col in range(6)]for row in range(len(psnr_bitrate_1080))] for x in range(2)]

and I want to put a and b into c and for this, I use the following code:

c[:][:][0]=a
c[:][:][1]=b

but it does nothing and all values in c are still zero and it does not replace the values in c with a and b. do you know what is the problem? the rows and columns in c are lists while a and b are arrays. I try to make a 3D array with values of a and b. I do not know why it can not do correctly. please tell me how can I do this. Thanks.

CodePudding user response:

If you want to "stack" two 2-D arrays, then the most intuitive method is to use dstack:

c = np.dstack((a, b))

This way you don't even need to create any empty array before.

But if you want to stack your both source arrays "along another axis" (as I see from your comment), run e.g.:

c2 = np.swapaxes(c, 1, 2)

Then c2[:,0,:] will return your first source array.

  • Related