【问题标题】:Convert netCDF file to csv using Python使用 Python 将 netCDF 文件转换为 csv
【发布时间】:2018-05-10 05:38:58
【问题描述】:

我正在尝试将 netCDF 文件转换为 csv。文件存储在 thredds 服务器中。我在下面编写了从其中读取文件的代码 Thredds 服务器并从 netCDF 文件中存在的变量列表中选择六个变量,并将它们以 csv 格式存储在本地。

from datetime import datetime
from netCDF4 import Dataset
import netCDF4
import pandas as pd
import csv
def get_thredds_url(datetime_group, forecast_hour):
    base_url="path"
    thredds_url="path"
    cycle_hour = "%02d" % datetime_group.hour
    file_str=datetime_group.strftime("%Y%m%d%H")+"/gfs.t%sz.pgrb2.0p25.f%03d" % \
        (cycle_hour, forecast_hour)
    url = base_url + thredds_url + file_str
    return (url)

下面的代码显示了所需的变量。

def main():

    datetime_group = datetime(2017, 9, 26, 0)
    forecast_hour = 240

    url = get_thredds_url(datetime_group, forecast_hour)
    print (url)

    nc_handle=Dataset(url)
    #print (nc_handle.variables.keys())
    lat=nc_handle.variables['lat'][:]
    lon=nc_handle.variables['lon'][:]
    issue_time=nc_handle.variables['time'][:]
    valid_time=nc_handle.variables['time1'][:]
    temp=nc_handle.variables['Temperature_height_above_ground'][:]
    dewpoint_temp=lat=nc_handle.variables['Dewpoint_temperature_height_above_ground'][:]
    dtime = netCDF4.num2date(issue_time[:],units=units)


 tmp = pd.Series(temp, index=dtime) 

    tmp.to_csv('temp.csv',index=True, header=True)
    csvwriter = csv.writer(tmp,  delimiter=',')
    print (csvwriter)





if __name__ == "__main__":
    main()

问题:我无法将文件写入包含 lat、lon、time、time1、Temperature_height_above_ground 等所有变量的 csvnformat。期望的输出如下:

tmp.csv

 lat lon time time1 Temperature_height_above_ground
1 ... .. ...  ....  ......
2 ... .. ...  ....  ......
3 ... .. ...  ....  ......

谁能帮我解决这个问题?

提前致谢!

【问题讨论】:

  • 这个问题并没有说明确切的问题是什么。请参阅stackoverflow.com/help/how-to-ask 以获得一些指导并编辑您的问题以添加例如一条错误消息。当您使用它时,将您的帖子的缩进修复为“问题:我无法...”行目前看起来它是源代码的一部分,我认为这是不正确的。

标签: python csv netcdf netcdf4


【解决方案1】:

我认为您正在寻找的是:

with open('temp.csv', 'w') as f:
  writer = csv.writer(f, delimiter=',')
  # write the header
  writer.writerow(['lat',
                   'lon',
                   'time',
                   'time1',
                   'temp_height_above_ground',
                   'dewpoint_temp_height_above_ground',
                   'issue_time'])

  # collect the columns as rows
  rows = zip(lat,lon,issue_time,valid_time,temp,dewpoint_temp,dtime)

  for row in rows:
    writer.writerow(row)

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 2019-09-20
    • 1970-01-01
    • 2018-12-24
    • 2021-06-21
    • 1970-01-01
    • 2015-05-19
    • 2014-05-20
    • 2021-09-07
    相关资源
    最近更新 更多