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

15

我正在尝试以最简单/最快的方式学习如何使用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,:],我试图更改它,但无法编译;但我不明白它在做什么以及为什么使用这些数字。


1
".nc"文件是什么?它包含文本还是二进制数据? - skrrgwasme
这是netcdf扩展名。 - Alessandro
1
包含二进制数据。 - Alejandro Jiménez Rico
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)

1
如果你能解释一下数据读取过程中的每一行代码的功能,那就太好了。 - Alfredo Hernández
哇,我爱你。通常情况下,我不知道我的变量是什么。我该如何找出我的变量是什么? - Alejandro Jiménez Rico
1
我无法在我的机器上使用netcdf4,因此我不知道您如何使用它。从bash中的一个简单方法是ncdump -h filename,它会绘制netcdf文件中的所有变量。使用我使用的netcdf.NetCDFFile,您还可以执行print(file2read.variables.keys()),以获取文件中所有变量的列表。 - Alessandro
无论如何,请记住状态文件中的变量始终为'Temp'、'S'、'V'、'U'、'W'和'Eta'。而其他输出文件中的变量将在您的data.diagnostics中指定。 - Alessandro

11

对于带有Python 3的netCDF4文件,请使用:

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'])

或者查看您的netcdf4文件中的所有变量,只需打印“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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接