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

ali*_*i43 1 python csv text netcdf netcdf4

我正在尝试使用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'][:]
Run Code Online (Sandbox Code Playgroud)

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

Eri*_*ger 10

我认为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)
Run Code Online (Sandbox Code Playgroud)

  • 不客气。您应该接受未来读者的答案。 (2认同)

Rob*_*avy 7

import xarray as xr

nc = xr.open_dataset('file_path')
nc.precip.to_dataframe().to_csv('precip.csv')
Run Code Online (Sandbox Code Playgroud)


Mac*_*Mac 2

根据您的要求,您也许可以使用 Numpy 的savetxt方法:

import numpy as np

np.savetxt('lat.csv', lat, delimiter=',')
np.savetxt('lon.csv', lon, delimiter=',')
np.savetxt('precip.csv', precip, delimiter=',')
Run Code Online (Sandbox Code Playgroud)

但是,这将输出没有任何标题或索引列的数据。

如果您确实需要这些功能,您可以构建一个 DataFrame 并将其保存为 CSV,如下所示:

df_lat = pd.DataFrame(data=lat, index=dtime)
df_lat.to_csv('lat.csv')

# and the same for `lon` and `precip`.
Run Code Online (Sandbox Code Playgroud)

注意:在这里,我假设日期/时间索引沿着数据的第一个维度运行。