2017-06-04 84 views
0

我想将netCDF文件转换为使用Python的CSV或文本文件。我读过this post,但我仍然缺少一个步骤(我是Python新手)。这是一个包含纬度,经度,时间和降水量数据的数据集。使用Python将NetCDF文件转换为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'][:] 

我不知道如何从这里出发,虽然我知道这是创建与大熊猫一个数据帧的问题。

回答

1

根据您的要求,您可以使用与NumPy的savetxt方法:

import numpy as np 

np.savetxt('lat.csv', lat, delimiter=',') 
np.savetxt('lon.csv', lon, delimiter=',') 
np.savetxt('precip.csv', precip, delimiter=',') 

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

如果你确实需要这些功能,您可以构建一个数据帧,并将其保存为CSV如下:

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

# and the same for `lon` and `precip`. 

注:在这里,我假定日期/时间指数沿的第一维运行数据。

+0

谢谢!不幸的是,这并没有奏效 - 我决定只提取我在其他数据集中使用的所有纬度和经度,然后循环播放以获取每个地点的时间序列。就像我在上面提供的链接一样。耗时,但它的工作原理! – aliki43

2

我认为pandas.Series应该为你工作创建一个CSV与时间,拉特,lon,沉淀。

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) 
+0

谢谢!这是完美的 – aliki43

+0

不客气。你应该接受未来读者的答案。 –

相关问题