![](/img/trans.png)
[英]Read netcdf4 variable attributes and write them to variables of new file
[英]Read values from a NetCDF file and write them to a csv file
我有一個帶有此信息的NetCDF文件:
尺寸:
lon = 238;
lat = 132;
dep = 38;
time = 8;
變量:
float lon(lon=238);
float lat(lat=132);
float dep(dep=38);
double time(time=8);
float eastward_sea_water_velocity(time=8, dep=38, lat=132, lon=238);
float northward_sea_water_velocity(time=8, dep=38, lat=132, lon=238);
我想讀取lon,lat,eastward_sea_water_velocity和northward_sea_water_velocity,並將值寫入csv文件。
因此,csv文件將如下所示:
Lon Lat E-Vel N-Vel
28.4511 41.8866 -3.7 -6.3
直到現在,我僅成功讀取lon和lat並將它們寫入csv:
x,y = ncfile.variables['lon'], ncfile.variables['lat']
import csv
with open('text2.csv', 'w') as f:
writer = csv.writer(f, delimiter='\t')
header = ['Longitude', 'Latitude']
writer.writerow(header)
writer.writerows(zip(x,y))
f.close()
當我嘗試使用以下代碼打印“ eastward_sea_water_velocity”中的值時:
temp = ncfile.variables['eastward_sea_water_velocity']
print temp
我的輸出是:
<type 'netCDF4.Variable'>
float32 eastward_sea_water_velocity(time, dep, lat, lon)
_FillValue: -999.0
missing_value: -999.0
units: m s-1
long_name: u-component of current
standard_name: eastward_sea_water_velocity
scale_factor: 0.01
add_offset: 0.0
source: MHI NASU Hydrodinamical model version V2
valid_min: -5.0
valid_max: 5.0
unlimited dimensions:
current shape = (8, 38, 132, 238)
那么,如何從變量“ eastward_sea_water_velocity”中讀取值?
提前非常感謝您! 祝一切順利 !
經度和緯度是一維變量,代表表示多維數據的x和y軸的水平坐標。 zip()
所做的是從每個列表中獲取項目對,因此即使您從該語句中獲得輸出,它也不會寫入文件中所有可能的lon,lat對。 由於eastward_sea_water_velocity
是4維的,因此問題甚至更大。 為簡單起見,我們假設您只需要固定時間和深度的二維數據切片:
lon = ncfile.variables['lon']
lat = ncfile.variables['lat']
# Grab 2D slice for time index 0 and depth index 0
u = ncfile.variables['eastward_sea_water_velocity'][0, 0]
import csv
import numpy as np
with open('text2.csv', 'w') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow(['Longitude', 'Latitude', 'E-Vel'])
for inds,val in np.ndenumerate(u):
writer.writerow([lon[inds[0]], lat[inds[1]], val])
使用print temp[:]
或根據變量print temp[:,:,:,:]
的形狀
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.