使用 Python 将 NetCDF 文件转换为 CSV 或文本 [英] Convert NetCDF file to CSV or text using Python

查看:25
本文介绍了使用 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.

这是我目前的代码:

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 创建数据框的问题.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆