python讀寫nc文件

參考自

http://nbviewer.jupyter.org/url/bitbucket.org/yingkaisha/python-in-remote-sensing/raw/aec6a23e8580d1cba4fb485d024c13f061350fe7/Python%20Solutions%20for%20Unpacking%20Scientific%20Datasets.ipynb


#讀nc文件需要用到netCDF4
import netCDF4 as nc


#打開nc文件
nc_obj=nc.Dataset("C:\\Users\\kong\\PycharmProjects\\replacencl\\meow")


#看看NC文件中有甚麼
print(nc_obj)

<type 'netCDF4._netCDF4.Dataset'>
root group (NETCDF3_CLASSIC data model, file format NETCDF3):
    TITLE:  OUTPUT FROM WRF V3.3.1 MODEL
    START_DATE: 2008-07-30_00:00:00
    SIMULATION_START_DATE: 2008-07-30_00:00:00
    ...
    dimensions(sizes): Time(1), DateStrLen(19), west_east(669), south_north(669),...
    variables(dimensions): |S1 Times(Time,DateStrLen), float32 LU_INDEX(Time,south_north,west_east), float32 ZNU(Time,bottom_top), ...
    groups: 


#查看nc文件中的變量
print(nc_obj.variables.keys())
[u'Times', u'LU_INDEX', u'ZNU', u'ZNW', u'ZS', u'DZS',...


#查看U這個變量
print(nc_obj.variables['U'])
<type 'netCDF4._netCDF4.Variable'>
float32 U(Time, bottom_top, south_north, west_east_stag)
    FieldType: 104
    MemoryOrder: XYZ
    description: x-wind component
    units: m s-1
    stagger: X
    coordinates: XLONG_U XLAT_U
unlimited dimensions: Time
current shape = (1, 39, 669, 670)
filling off


#查看U這個變量的屬性
print(nc_obj.variables['U'].ncattrs())
[u'FieldType', u'MemoryOrder', u'description', u'units', u'stagger', u'coordinates']


#查看U的其中一個屬性「單位」
print(nc_obj.variables['U'].units)
m s-1



#<span style="background-color: rgb(240, 240, 240);">讀取U的數據值</span>
UU=nc_obj.variables['U'][:]
print(UU)

[[[[ -1.23765385e+00  -1.18628418e+00  -1.13026094e+00 ...,
        ...,
        ...,
        ...,

     -2.50045204e+00  -2.50769806e+00  -2.52506447e+00]]]]

#隨便畫個直方圖看看吧
plt.hist(UU[0,0,0,:], color='gray')
plt.show()


#關閉文件
nc_obj.close()


#新建文件並寫入數據
da=nc.Dataset("950hPa_llj_ageouvznum","w",format="NETCDF4")
da.createDimension("latsize",usize[0])
da.createDimension("lonsize",usize[1])
da.createVariable("u","f8",("latsize","lonsize"))
da.createVariable("v","f8",("latsize","lonsize"))
da.createVariable("z","f8",("latsize","lonsize"))
da.createVariable("lon","f8",("latsize","lonsize"))
da.createVariable("lat","f8",("latsize","lonsize"))
da.createVariable("num","f8",("latsize","lonsize"))
da.variables["u"][:]=output_u
da.variables["v"][:]=output_v
da.variables["z"][:]=output_z
da.variables["lat"][:]=lat
da.variables["lon"][:]=lon
da.variables["num"][:]=output_num
da.description="950hPa,LLJ,ageouvznum"
da.author="konghoiio"
da.createdate="2016-10-05"
da.close()





评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值