使用 Python 将 NetCDF 文件转换为 CSV 或文本

新手上路,请多包涵

我正在尝试使用 Python 将 netCDF 文件转换为 CSV 或文本文件。我已经阅读 了这篇文章,但我仍然缺少一个步骤(我是 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'][:]

我不确定如何从这里开始,但我知道这是用熊猫创建数据框的问题。

原文由 aliki43 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
1 个回答

我认为 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)

原文由 Eric Bridger 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏