我正在尝试使用 Python 将 netCDF 文件转换为 CSV 或文本文件。我读过this post但我仍然缺少一个步骤(我是 Python 的新手)。它是一个包含纬度、经度、时间和降水量数据的数据集。
到目前为止,这是我的代码:
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'][:]
我不确定如何从这里开始,但我知道这是用 pandas 创建数据框的问题。
请您参考如下方法:
我认为 pandas.Series 应该可以帮助您创建包含时间、纬度、经度、降水量的 CSV。
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)
