使用Python将NetCDF文件转换为CSV或文本 [英] Convert NetCDF file to CSV or text using Python
本文介绍了使用Python将NetCDF文件转换为CSV或文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Python将netCDF文件转换为CSV或文本文件.我已阅读这篇文章,但我仍然缺少一个步骤(我是Python新手).它是一个包含纬度,经度,时间和降水量数据的数据集.
I'm trying to convert a netCDF file to either a CSV or text file using Python. I have read this post but I am still missing a step (I'm new to Python). It's a dataset including latitude, longitude, time and precipitation data.
到目前为止,这是我的代码:
This is my code so far:
import netCDF4
import pandas as pd
precip_nc_file = 'file_path'
nc = netCDF4.Dataset(precip_nc_file, mode='r')
nc.variables.keys()
lat = nc.variables['lat'][:]
lon = nc.variables['lon'][:]
time_var = nc.variables['time']
dtime = netCDF4.num2date(time_var[:],time_var.units)
precip = nc.variables['precip'][:]
我不确定如何从此处开始,尽管我知道这是使用熊猫创建数据框的问题.
I am not sure how to proceed from here, though I understand it's a matter of creating a dataframe with pandas.
推荐答案
我认为pandas.Series
应该可以帮助您创建带有时间,纬度,经度和降水量的CSV.
I think pandas.Series
should work for you to create a CSV with time, lat,lon,precip.
import netCDF4
import pandas as pd
precip_nc_file = 'file_path'
nc = netCDF4.Dataset(precip_nc_file, mode='r')
nc.variables.keys()
lat = nc.variables['lat'][:]
lon = nc.variables['lon'][:]
time_var = nc.variables['time']
dtime = netCDF4.num2date(time_var[:],time_var.units)
precip = nc.variables['precip'][:]
# a pandas.Series designed for time series of a 2D lat,lon grid
precip_ts = pd.Series(precip, index=dtime)
precip_ts.to_csv('precip.csv',index=True, header=True)
这篇关于使用Python将NetCDF文件转换为CSV或文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文