如何转换为长度为1的数组?

时间:2014-05-08 16:27:00

标签: arrays python-2.6 netcdf scalar

我打开了一个有两个变量的netCDF文件。每个变量有4个维度: 时间,高度,纬度和经度。

我正在使用循环遍历每个纬度的脚本(i)&经度步骤(j)并将数据传递到浮点格式并写入我的输出文件,虽然我收到此错误:

utemp = float(uwind[i][i][j])  # data 
TypeError: only length-1 arrays can be converted to Python scalars

我在这里给你正在使用的编码。

阅读篇幅:

tstep = range(len(time))
lonstep = range(len(lon))
latstep = range(len(lat))

设置变量:

time = ncfile.variables['time']
lat = ncfile.variables['lat']
lon = ncfile.variables['lon'] 
uwind = ncfile.variables['10u']  

写入文件:

for t in tstep:
  for i in latstep:      
    for j in lonstep:      
      utemp = float(uwind[t][i][j])  
      windfile.write('%.4f '%utemp)  

任何人都可以帮助我将变量转换为正确的格式,而不会出现错误吗?

这是我所做的更改,它似乎在停止之前写入文件:

    for t in tstep:     

   windfile.write(header+'\n')    
   for hts in htstep:
      for i in latstep:     
         for j in lonstep:     
            utemp = float(uwind[hts][t][i][j])  # data 
            windfile.write('%.4f '%utemp)  
         windfile.write('\n')
   for hts in htstep:
      for i in latstep:
         for j in lonstep:
            vtemp = float(vwind[hts][t][i][j])
            windfile.write('%.4f '%vtemp)
         windfile.write('\n')
windfile.close() 

从那我得到

Traceback (most recent call last):
  File "CFSR2SWAN.py", line 52, in <module>
    utemp = float(uwind[hts][t][i][j])  # data 
IndexError: index out of bounds

如果有人可以看看,我将不胜感激

谢谢

2 个答案:

答案 0 :(得分:1)

你说uwind是在每个纬度,经度,高度和时间定义的,但是当你调用uwind[i][i][j]时,你只给出三个指数。因此输出将是一维阵列。给出第四个索引,例如uwind[i,i,j,j]应解决错误。

但是,从概念上讲,我不确定为什么你在前两个维度使用latstep索引i。如果您只是尝试将数组写入外部文件,请考虑pickle(或cPickle)内置库。 (循环每个网格点和时间是非常低效的。)

另外,我假设你正在使用netCDF4模块,在这种情况下不需要float()转换 - 这些值已经是浮点数(你可以测试,例如type(uwind[0,0,0,0])。

答案 1 :(得分:0)

只是评论和解决方案的总和,Spencer Hill(在评论中)帮助我指导解决方案。

最初的问题是并非所有维度都分配给temp值,每个netCDF文件通常有3个或更多维度(除了包含的数据集),在这种情况下,3个额外的维度,其中时间(t),身高(ht),纬度(纬度),经度(lon)。

要查看netCDF中包含的数据,可以在Matlab中使用>ncdump -h fnamencdsip,经过一些搜索我发现即使可以看到变量python&#39; s构建在netCDF模块中以不同的逻辑打开它们。

因此,在一个人注册了文件中包含的数据并在python中识别它们之后

>>>shape(uwind)

你会得到类似的东西

(8737, 1, 5, 9)

如果使用ncdump或ncdisp,变量维度的表示可能会有所不同。

所以最初我有这行代码,因为我正在使用ncdump来打开&#34; Linux / UNIX中文件的内容

utemp = float(uwind[hts][t][i][j])

产生错误提及。

当我在python中尝试>shape(varname)时,我将temp重写为

 vtemp = float(vwind[t][hts][i][j])

然后代码写得正确

我希望它会有所帮助