使用python读取.nc(netcdf)文件

问题描述 投票:0回答:3

我正在尝试学习如何使用Python以最简单/最快的方式读取netcdf文件。听说3行代码就可以搞定,但是我真的不知道怎么做。

我正在运行 MITgcm 数值模型。我正在尝试找到一种简单的方法来可视化输出数据,其方式与 NCview 等程序相同,但使用 Python,这样我就可以自定义要读取的参数和所有内容。

我发现了这个:

from matplotlib import pyplot as plt
import pandas as pd
import netCDF4
fp='uwstemp.nc'
nc = netCDF4.Dataset(fp)
plt.imshow(nc['Temp'][1,:,0,:])
plt.show()

它大致按照我想要的方式工作,但我想逐字理解它在做什么。我猜“Temp”是我的变量之一,但我不知道如何弄清楚我的所有变量是什么。

特别是,我不明白

plt.imshow(nc['Temp'][1,:,0,:])
[1,:,0,:] 我尝试更改它但无法编译;但我不明白它在做什么以及为什么这个数字。

python netcdf
3个回答
17
投票

我也使用 MITgcm。假设您有 state.nc 输出。 首先,确保导入所需的所有内容:

from scipy.io import netcdf
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

读取数据最简单的方法是:

file2read = netcdf.NetCDFFile(path+'state.nc','r')
temp = file2read.variables[var] # var can be 'Theta', 'S', 'V', 'U' etc..
data = temp[:]*1
file2read.close()

然后在时间 t 绘制 z 层的快速方法是:

plt.contourf(data[t,z,:,:])

为了回答你的问题,我评论了代码:

from matplotlib import pyplot as plt # import libraries
import pandas as pd # import libraries
import netCDF4 # import libraries
fp='uwstemp.nc' # your file name with the eventual path
nc = netCDF4.Dataset(fp) # reading the nc file and creating Dataset
""" in this dataset each component will be 
in the form nt,nz,ny,nx i.e. all the variables will be flipped. """
plt.imshow(nc['Temp'][1,:,0,:]) 
""" imshow is a 2D plot function
according to what I have said before this will plot the second
iteration of the vertical slize with y = 0, one of the vertical
boundaries of your model. """
plt.show() # this shows the plot

如果您想检查数据的各个维度,以便知道可以绘制什么,只需执行以下操作

print(nc['Temp'].shape)


12
投票

对于 netCDF4 文件(使用 python 3),请使用:

import netCDF4
file2read = netCDF4.Dataset(cwd+'\filename.nc','r')
var1 = file2read.variables['var1']  # access a variable in the file

其中 cwd 是我当前的工作目录,用于获取 .nc 文件的文件路径以便读取它:

import os
cwd = os.getcwd()

我使用的是 Windows,因此文件目录与 Mac 或 Linux 不同。

查看所有可变键:

print(file2read.variables.keys())

这将给出如下输出:

dict_keys(['ap', 'ap_bnds', 'b', 'b_bnds', 'bnds', 'ch4', 'lat', 'lat_bnds', 'lev', 'lev_bnds', 'lon', 'lon_bnds', 'time', 'time_bnds'])

或者要查看 netcfd4 文件中的所有变量,您只需打印“file2read”即可:

print(file2read)

输出将包含类似这样的内容(具体看最后):

source_id: GFDL-ESM4
source_type: AOGCM AER CHEM BGC
sub_experiment: none
sub_experiment_id: none
title: NOAA GFDL GFDL-ESM4 model output prepared for CMIP6 update of RCP8.5 based on SSP5
variable_id: ch4
variant_info: N/A
references: see further_info_url attribute
variant_label: r1i1p1f1
dimensions(sizes): lev(49), bnds(2), time(1032), lat(180), lon(288)
variables(dimensions): float64 ap(lev), float64 ap_bnds(lev, bnds), float64 b(lev), float64 b_bnds(lev, bnds), float64 bnds(bnds), float32 ch4(time, lev, lat, lon), float64 lat(lat), float64 lat_bnds(lat, bnds), float64 lev(lev), float64 lev_bnds(lev, bnds), float64 lon(lon), float64 lon_bnds(lon, bnds), float64 time(time), float64 time_bnds(time, bnds)

您可以注意到最后一部分包括变量的维度以及变量的类型和名称。

查看此网站以获取更多信息和示例: https://www.earthinversion.com/utilities/reading-NetCDF4-data-in-python/


2
投票

如果您在 Linux 中工作,我的软件包 nctoolkit (toolkit.readthedocs.io/en/latest/) 提供与 ncview 类似的功能,但在 Python 中。它可以在 Jupyter 笔记本或 Web 浏览器中自动绘制 NetCDF 文件的内容。以下应该适用于给定的数据:

import nctoolkit as nc
fp='uwstemp.nc'
data = nc.open_data(fp)
data.plot()
© www.soinside.com 2019 - 2024. All rights reserved.