简体   繁体   English

如何在循环中使用numpy从python中的2D数组高效创建3D数组?

[英]How to efficiently create a 3D array from 2D arrays in python using numpy in a loop?

I am extracting variables in NetCDF files. 我正在提取NetCDF文件中的变量。 These files are very big and I would prefer a minimum number of loops. 这些文件很大,我希望循环次数最少。 Each variable is 162x174 and I have around 200 such files. 每个变量是162x174,我大约有200个这样的文件。 I want a variable in the end like in Matlab which is 3d - 162x174x200. 我最后想要一个像Matlab中那样的变量,它是3d-162x174x200。

In the code, apart from append, I tried dstack and vstack but they did not work either. 在代码中,除了追加,我尝试了dstack和vstack,但是它们都不起作用。 I am also not sure the concatenation will occur like - 2x162x174 or 162x174x2. 我也不确定串联会像2x162x174或162x174x2那样发生。

 from netCDF4 import Dataset
 import os 
 import wrf 
 import numpy as np 
 import glob

 os.chdir(r'G:\WRF')
 ctt_wrf=[]
 for file in glob.glob('wrfout_*'):
    ncfile = Dataset(file)
    ctt=wrf.getvar(ncfile, "ctt")
    ctt_wrf.append(ctt)

 np.array(ctt_wrf).shape

如果每个文件中的数据都是原子的,则您可能最终希望得到一个数组,该数组的大小为:number_of_files x 162 x 174,在这种情况下,您使用的方法的形状为200 x 162 x 174

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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