【问题标题】:How can I extract netCDF to csv for a specific location?如何将 netCDF 提取到特定位置的 csv?
【发布时间】:2019-08-29 09:55:09
【问题描述】:

我想将时间序列从 NetCDF 提取到特定位置的 csv。 我的代码到此为止,但它给出了 TypeError: a bytes-like object is required, not 'str'

我该如何克服这个问题? 另外,这个开发的代码是否会有输出:time/mwp for the specific location?

import netCDF4 
import pandas as pd
import matplotlib.pyplot as plt
import csv
import numpy as np
from netCDF4 import Dataset, num2date
from pylab import *
import xarray

f = netCDF4.Dataset('Wave_period_global.nc')
f.variables.keys()
print (f)

lat = f.variables['latitude'][:]
lon = f.variables['longitude'][:]
time_var = f.variables['time']
dtime = netCDF4.num2date(time_var[:],time_var.units)
mwp = f.variables['mwp'][:]

print(lon.min(), lon.max())
print(lat.min(), lat.max())

longitude = 172
latitude = 50

def near(array,value):
    idx=(abs(array-value)).argmin()
    return idx

ix = near(lat, latitude)
iy = near(lon, longitude)

print ('Latitude =',ix)
print ('Longitude =',iy)

with open ('Wave_period_global.csv', 'wb') as csvfile:
    filewriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for ln in range(len(lon)):
        for lt in range(len(lat)):
            value=f.variables['mwp'][0][lt][ln]
            dtime = netCDF4.num2date(time_var[0],time_var.units)
            print(dtime,lat[lt],lon[ln,],value)
            filewriter.writerow([dtime,lat[lt],lon[ln,],value])

【问题讨论】:

  • 哪个库给了你例外? netCDF4 还是 csv?你的逻辑是错误的。 ix 和 iy 被发现但未使用。当您需要一直循环时,您的 csv 循环会遍历所有纬度和经度。您需要先解决此问题,然后才能给出任何答案。

标签: python csv netcdf


【解决方案1】:

请参阅我上面的评论。我将把输出作为 csv 留在我的回答中,以专注于您的真正问题。

from netCDF4 import Dataset, num2date

f = netCDF4.Dataset('Wave_period_global.nc')

lat = f.variables['latitude'][:]
lon = f.variables['longitude'][:]
time_var = f.variables['time']
# These are all datetime object.
dtime = netCDF4.num2date(time_var[:],time_var.units)
mwp = f.variables['mwp'][:]

print(lon.min(), lon.max())
print(lat.min(), lat.max())

longitude = 172
latitude = 50

def near(array,value):
    idx=(abs(array-value)).argmin()
    return idx

ix = near(lat, latitude)
iy = near(lon, longitude)

print ('Latitude =',ix)
print ('lat[] =', lat[ix])
print ('Longitude =',iy)
print ('lon[] =', lon[iy])

for i in range(len(dtime)):
  value=f.variables['mwp'][i][ix][iy]
  print(dtime[i],lat[ix],lon[iy,],value)

【讨论】:

  • 用于导出到.csv;我尝试使用 'w' 而不是 'wb' 但这会改变 .csv 的输出......我现在仍然坚持导出到 .csv
  • dtime[i] 是一个 python 日期时间对象。对于 csv 你需要一个字符串。尝试 datetime[i].isoformat() 获取字符串。
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 2021-04-15
  • 2022-01-27
  • 2016-06-07
  • 2020-03-10
  • 2020-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多