0

我想问一些事情。我正在尝试运行下面显示的代码。但是第 40 行,在

time_dim, lat_dim, lon_dim = t2m.get_dims ()

我得到错误

ValueError: too many values to unpack (expected 3). 

我该如何解决这个问题。你能帮我吗?

我的代码如下:

import cdsapi
import netCDF4
from netCDF4 import num2date
import numpy as np
import os
import pandas as pd
 
# Retrieve data and store as netCDF4 file
c = cdsapi.Client()
file_location = 'r"C:\Users\A\Desktop\download.nc"'
c.retrieve(
    'reanalysis-era5-single-levels',
    {
        'product_type':'reanalysis',
        'variable':'2m_temperature',  # 't2m'
        'year':'2019',
        'month':'06',
        'day':[
            '24','25'
        ],
        'time':[
            '00:00','06:00','12:00',
            '18:00'
        ],
        'format':'netcdf'
    },
    file_location)
 
# Open netCDF4 file
f = netCDF4.Dataset(file_location)
 
# Extract variable
t2m = f.variables['t2m']
 
# Get dimensions assuming 3D: time, latitude, longitude
time_dim, lat_dim, lon_dim = t2m.get_dims()
time_var = f.variables[time_dim.name]
times = num2date(time_var[:], time_var.units)
latitudes = f.variables[lat_dim.name][:]
longitudes = f.variables[lon_dim.name][:]
 
output_dir = './'
4

2 回答 2

0

基本上,您正在尝试将输出分配给t2m.get_dims()3 个变量:

  • time_dim,
  • lat_dim,
  • lon_dim

然而,实际上,调用t2m.get_dims()返回超过 3 个值
这就是为什么你有错误:too many values to unpack


疑难解答:

✅ 第 1 步 > 将返回值分配给列表(输出) > outputs = t2m.get_dims()
✅ 第 2 步 > 打印输出以查看列表元素 > print(outputs)
✅ 第 3 步 > 找出哪些索引对应于 , , 的哪个值time_dimlat_dimlon_dim
4 步 > 分配值基于相应的索引,例如:time_dim = outputs[0]

于 2021-01-29T09:25:04.740 回答
0

谢谢你的解决方案。看起来没问题。当我添加代码以 CSV 格式下载时,遇到以下情况。我不明白为什么会这样。我添加的代码:将数据写成一个有 4 列的表:时间、纬度、经度、值

filename = os.path.join (output_dir, 'table.csv')
print (f'Writing data in tabular form to {filename} (this may take some time) ... ')
times_grid, latitudes_grid, longitudes_grid = [
    x.flatten () for x in np.meshgrid (times, latitudes, longitudes, indexing = 'ij')]
df = pd.DataFrame ({
    'time': [t.isoformat () for t in times_grid],
    'latitude': latitudes_grid,
    'longitude': longitudes_grid,
    't2m': t2m [:]. flatten ()))
df.to_csv (filename, index = False)
print ('Done')
================================================== ==
The situation I encountered:

  File "C: \ Users \ A \ Downloads \ untitled2.py", line 61, in <module>
    df = pd.DataFrame ({

  File "C: \ Users \ A \ anaconda3 \ lib \ site-packages \ pandas \ core \ frame.py", line 435, in __init__
    mgr = init_dict (data, index, columns, dtype = dtype)

  File "C: \ Users \ A \ anaconda3 \ lib \ site-packages \ pandas \ core \ internals \ construction.py", line 254, in init_dict
    return arrays_to_mgr (arrays, data_names, index, columns, dtype = dtype)

  File "C: \ Users \ A \ anaconda3 \ lib \ site-packages \ pandas \ core \ internals \ construction.py", line 64, in arrays_to_mgr
    index = extract_index (arrays)

  File "C: \ Users \ A \ anaconda3 \ lib \ site-packages \ pandas \ core \ internals \ construction.py", line 365, in extract_index
    raise ValueError ("arrays must all be same length")

ValueError: arrays must all be same length
于 2021-01-29T10:34:41.693 回答