2017-06-04 85 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

不客氣。你應該接受未來讀者的答案。 –

相關問題