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

时间:2016-04-01 15:43:36

标签: python

我正在尝试学习如何使用Python以最简单/最快的方式阅读.nc(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,:]我试图改变它并且不编译;但我不明白它在做什么以及为什么这个数字。

3 个答案:

答案 0 :(得分:2)

我也使用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 :(得分:0)

如果您在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()

答案 2 :(得分:0)

对于 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/