简体   繁体   English

如何在 python 的 netcdf 文件中读取变量的值?

[英]How can I read values of a variable in a netcdf file in python?

I have a NetCDF file called air.sig995.2012.nc .我有一个名为air.sig995.2012.nc的 NetCDF 文件。 it has four variables: ('lat','lon','time','air') .它有四个变量: ('lat','lon','time','air')

I am trying to read the values of any of the variables, lets say the variable air using below line:我正在尝试读取任何变量的值,让我们说变量air使用下面的行:

import scipy.io.netcdf as S
fileobj=S.netcdf_file('air.sig995.2012.nc','r')
data=fileobj.variables['air'].getValue()

but it gives me below error:但它给了我以下错误:

ValueError: can only convert an array of size 1 to a Python scalar ValueError:只能将大小为 1 的数组转换为 Python 标量

I am fairly new to python.我对 python 相当陌生。 Can anyone help me on this one.谁能帮我解决这个问题。

The output you're expecting is quite ambiguous but both methods should work depending on your specific goal in mind.您期望的 output 非常模棱两可,但两种方法都应该根据您的具体目标起作用。

`import xarray as xr `
### open netcdf file ###
df = xr.open_dataset('path/file.nc')

### extract values of variable 'air' ####
air = df['air'][:]
air_flat = df['air'].values.flatten() # 1-d data

If not xarray, you can do this with the netcdf4-python library with the same slice syntax:如果不是 xarray,您可以使用 netcdf4-python 库以相同的切片语法执行此操作:

from netCDF4 import Dataset

nc = Dataset('air.sig995.2012.nc')
my_array = nc.variables['air'][:]

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

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