使用Python将netCDF文件转换为csv

pod7payv  于 2022-12-06  发布在  Python
关注(0)|答案(2)|浏览(212)

我试图将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,time 1,Temperature_height_above_ground)的文件写入csvnformat。所需的输出如下:

tmp.csv

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

有谁能帮我解决这个问题吗?
提前感谢!

hl0ma9xz

hl0ma9xz1#

我想你要找的是:

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)
798qvoo8

798qvoo82#

您可以使用以下Python中的简单代码将NETCDF转换为CSV:-我们需要2个主库

a-NetCDF-4:-*(Network Common Data Form,version 4)说明. NetCDF是一组软件库与自我描述得,与机器无关得数据格式,用于面向阵列得科学数据 *
b-xarray:- xarray(以前是xray)是一个开源项目和Python包,它使处理带标签的多维数组变得简单、高效和有趣!
1-导入库

import netCDF4 as nc
    import xarray as xr

    data = nc.Dataset(r'C:\\Users\\Admin\\Desktop\\LDN DATA NC FORMAT\\20210312_0257.nc', 'r')
    dataset = xr.open_dataset(xr.backends.NetCDF4DataStore(data))
    df = dataset.to_dataframe()
    csv_data=df.to_csv('C:\\Users\\Admin\\Desktop\\LDN DATA NC FORMAT\\20210312_0257.nc.csv')
    print('\nCSV String:\n', csv_data)

图像1:-x1c 0d1x
图像2:-

完成执行后,将csv文件保存在提供的同一文件夹中

相关问题