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)


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'])

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



#讀取U的數據值
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()





你可能感兴趣的:(Python黑科技,ATMOS)