重塑从NC文件提取的三维阵列的形状

2024-06-02 09:10:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我提取了一个包含3个变量的NC文件,即经度、纬度和时间。代码如下:

from netCDF4 import Dataset
import numpy as np
import pandas as pd

air = Dataset('tmax_0.5_daily_2012-2012.nc', 'r')
dims = air.dimensions
ndims = len(dims)
vars = air.variables
nvars = len(vars)
attrs = air.ncattrs
lon = air.variables['lon'][:]
lat = air.variables['lat'][:]
time = air.variables['time'][:]

lon、lat和时间的尺寸分别为360、720和366。当我试图用下面的代码提取一个特定位置的“air”数据时,它工作得很好,并给我一个1D数组,其中包含时间0到366之间的air数据

variable = air.variables['air'][:,23, 50]

其中:是时间(从开始到结束),23和50是特定经度和纬度的索引号

但是,当我需要从多个位置提取数据时,必须运行下面的代码:

variable = air.variables['air'][:,23:30, 50:55]

这将给我一个3D阵列,其中有35个单元(7(23:30)x5(50:55))和366个Z维度(时间)

我的问题是如何将这个3D数组提取到excel中,格式为从时间0到366的每个单元格“air”值在1列下排序,数据集包括35列(作为单元格的数量),其对应值从时间开始到结束都会显示出来

enter image description here


1条回答
网友
1楼 · 发布于 2024-06-02 09:10:59

可以将Numpy^{}(366, -1)一起使用,其中-1向Numpy指示必须从数组的长度推断剩余维度

from netCDF4 import Dataset
import numpy as np
import pandas as pd

# using a similar dataset
# http://schubert.atmos.colostate.edu/~cslocum/netcdf_example.html
air = Dataset('air.sig995.2012.nc', 'r')
print(np.array(air.variables['air']).shape)
# (366, 73, 144)

variable = np.array(air.variables['air'][:,23:30, 50:55])
print(variable.shape)
# (366, 7, 5)

x = variable.reshape(366,-1)
print(x.shape)
# (366, 35)

df = pd.DataFrame(x)
print(df)
df.to_excel('output.xls')

来自df

             0           1           2   ...          32          33          34
0    280.070007  280.350006  280.970001  ...  299.779999  299.630005  299.380005
1    279.470001  280.080017  280.650024  ...  298.429993  299.229980  299.220001
2    279.570007  279.880005  280.400024  ...  298.450012  299.220001  299.549988
..          ...         ...         ...  ...         ...         ...         ...
363  281.400024  282.770020  284.200012  ...  298.450012  298.350006  298.669983
364  277.250000  278.150024  279.369995  ...  298.549988  298.520020  298.520020
365  278.070007  277.520020  277.179993  ...  298.080017  298.799988  299.200012

[366 rows x 35 columns]

相关问题 更多 >