
我想使用netCDF4-Python从netCDF文件中选择变量,我使用以下代码:
import numpy as np
import pandas as pd
from pylab import *
from netCDF4 import Dataset
pals = Dataset('pals_amplero_2003_2006_ecmwf_v1.nc4', "a",format='NETCDF4')
print (pals.variables.keys())
print (pals.variables['Rainf'])
print (pals.variables['Evap'])
print (pals.variables['time'])
evap = pals.variables['Evap'][:,:]
rain = pals.variables['Rainf'][:,:]
subplot(2,1,1)
pcolor(evap)
subplot(2,1,2)
pcolor(rain)不幸的是,它输出了一条错误消息(在所附文档中有更详细的信息):
ValueError: too many values to unpack (expected 2)有关信息,以下是打印命令的输出
odict_keys(['DelIntercept', 'DelSWE', 'DelSoilMoist', 'Evap', 'Qs', 'Qsb', 'Qsm', 'Rainf', 'Snowf', 'lat', 'lon', 'nlevs', 'time', 'timestp', 'M_fieldcap', 'M_sat', 'M_wilt', 'SoilDepth', 'CanopInt', 'Conds', 'ECanop', 'ESoil', 'RootMoist', 'SubSnow', 'TVeg', 'DelColdCont', 'DelSoilHeat', 'LWnet', 'LWup', 'Qf', 'Qg', 'Qh', 'Qle', 'SWnet', 'Fdepth', 'HFLUXRF', 'IceFrac', 'MFLUXRF', 'SAlbedo', 'SnowDepth', 'SnowFrac', 'Tdepth', 'WSN', 'AvgSurfT', 'HLICE', 'HLML', 'SWE', 'SnowT', 'SoilMoist', 'SoilTemp', 'TLBOT', 'TLICE', 'TLMNW', 'TLSF', 'TLWML', 'icetemp', 'snowdens', 'Albedo', 'BaresoilT', 'RH2m', 'RadT', 'T2m', 'VegT', 'Bgain', 'Biomstr', 'Biomstr2', 'Bloss', 'biomass', 'lai', 'Ag', 'An', 'CO2flux', 'Rd', 'Reco', 'Rsoil_str'])
<class 'netCDF4._netCDF4.Variable'>
float32 Rainf(time, y, x)
units: mm/day
long_name: Rainfall rate
associate: time y x
missing_value: 1e+20
time_representation: average over past model timestep
unlimited dimensions: time
current shape = (70084, 1, 1)
filling on, default _FillValue of 9.969209968386869e+36 used
<class 'netCDF4._netCDF4.Variable'>
float32 Evap(time, y, x)
units: mm/day
long_name: Total evapotranspiration
associate: time y x
missing_value: 1e+20
time_representation: average over past model timestep
unlimited dimensions: time
current shape = (70084, 1, 1)
filling on, default _FillValue of 9.969209968386869e+36 used
<class 'netCDF4._netCDF4.Variable'>
float64 time(time)
units: seconds since 2003-01-01 00:00:00
long_name: Time in seconds
Time_label: Start of output interval
unlimited dimensions: time
current shape = (70084,)
filling on, default _FillValue of 9.969209968386869e+36 used发布于 2017-11-20 17:03:26
终于看到问题了。以这个例子(随机的NetCDF文件)为例:
ncdump -h th.xz.nc给予(除其他外):
float th(time, z, x, y) ;因此,变量th有4个维度。如果您以与代码类似的方式阅读/绘制此代码:
import netCDF4 as nc4
import matplotlib.pylab as pl
nc = nc4.Dataset('th.xz.nc')
th = nc.variables['th'][:,:]
pl.figure()
pl.pcolor(th)它给出了同样的错误:
ValueError:太多的值无法解包(预期的2)
为什么?使用[:,:] (或[:],或[:,:,:])切片仍然会给您提供两个以上的维度:
print(th.shape)(9、32、32、1)
而pcolor则需要一个二维数组。解决方案很简单;您需要选择要显示的2D片,例如pcolor(evap[0,:,:]) (x-y片)、pcolor(evap[:,0,:]) (time-x片)或.
https://stackoverflow.com/questions/47334454
复制相似问题