从 NetCDF 文件中读取值并将其写入 csv 文件



我有一个包含此信息的NetCDF文件:

尺寸:

lon = 238;
lat = 132;
dep = 38;
time = 8;

变量:

float lon(lon=238);
float lat(lat=132);
float dep(dep=38);
double time(time=8);
float eastward_sea_water_velocity(time=8, dep=38, lat=132, lon=238);
float northward_sea_water_velocity(time=8, dep=38, lat=132, lon=238);

我想读取 lon、lat、eastward_sea_water_velocity 和 northward_sea_water_velocity,并将值写入 csv 文件。

所以csv文件将是这样的:

Lon Lat E-Vel N-Vel
28.4511 41.8866 -3.7 -6.3

到目前为止,我只成功地阅读了lon和lat,并将它们写成csv:

x,y = ncfile.variables['lon'], ncfile.variables['lat']
import csv
with open('text2.csv', 'w') as f:
    writer = csv.writer(f, delimiter='t')
    header = ['Longitude', 'Latitude']
    writer.writerow(header)
    writer.writerows(zip(x,y))
f.close()

当我尝试使用以下代码打印"eastward_sea_water_velocity"中的值时:

temp = ncfile.variables['eastward_sea_water_velocity']
print temp

我的输出是:

<type 'netCDF4.Variable'>
float32 eastward_sea_water_velocity(time, dep, lat, lon)
_FillValue: -999.0
missing_value: -999.0
units: m s-1
long_name: u-component of current
standard_name: eastward_sea_water_velocity
scale_factor: 0.01
add_offset: 0.0
source: MHI NASU Hydrodinamical model version V2
valid_min: -5.0
valid_max: 5.0
unlimited dimensions: 
current shape = (8, 38, 132, 238)

那么,如何从变量"eastward_sea_water_velocity"中读取值?

提前非常感谢!万事如意!

经度

和纬度是一维变量,表示表示多维数据的 x 轴和 y 轴的水平坐标。zip()所做的是从每个列表中获取项目对,因此即使您从该语句中获得输出,它也不会写入文件中所有可能的 lon,lat 对。由于eastward_sea_water_velocity是 4 维的,因此问题更大。为简单起见,我们假设您只需要在固定时间和深度下查看此数据的 2D 切片:

lon = ncfile.variables['lon']
lat = ncfile.variables['lat']
# Grab 2D slice for time index 0 and depth index 0
u = ncfile.variables['eastward_sea_water_velocity'][0, 0]
import csv
import numpy as np
with open('text2.csv', 'w') as f:
    writer = csv.writer(f, delimiter='t')
    writer.writerow(['Longitude', 'Latitude', 'E-Vel'])
    for inds,val in np.ndenumerate(u):
      writer.writerow([lon[inds[0]], lat[inds[1]], val])

使用print temp[:]或取决于变量print temp[:,:,:,:]的形状

当我尝试用这个打印时:

print temp[:,:,:,:]

输出为:

[[[[-- -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]
..., 
[-- -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]]

但是,我确定变量有值,因为我使用 Panoply 打开文件,我看到了值。

PS:也许Jules0080来自这篇文章,可以帮助我

最新更新