python中的.nc文件处理 | 03 指定位置的数据切片及可视化
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                python中的.nc文件处理 | 03 指定位置的数据切片及可视化
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.                        
                                NetCDF4文件處理
- 下載MACA v2的 netcdf4 格式數(shù)據(jù)
 - 使用 xarray 讀取和處理 netcdf4 格式數(shù)據(jù)
 - 將 netcdf4 格式數(shù)據(jù)導(dǎo)出為 .csv 格式
 - 將 netcdf4 格式數(shù)據(jù)導(dǎo)出為 .tif 格式
 
參考鏈接
import osimport numpy as np import pandas as pd import matplotlib.pyplot as plt # 處理netcdf4文件所要用到的包 import xarray as xr import rioxarray import cartopy.crs as ccrs import cartopy.feature as cfeature import seaborn as sns import geopandas as gpd import earthpy as et# 統(tǒng)計(jì)圖繪制選項(xiàng) sns.set(font_scale=1.3) sns.set_style("white")文件讀取
.nc文件名的含義
agg_macav2metdata_tasmax_BNU-ESM_r1i1p1_historical_1950_2005_CONUS_monthly
- agg_macav2metdata :MACA v2版本,降尺度到美國大陸
 - tasmax :數(shù)據(jù)項(xiàng)為最高溫度
 - BNU-ESM :產(chǎn)生該原始數(shù)據(jù)的模式名稱
 - historical :數(shù)據(jù)為1950-2005年的歷史預(yù)測數(shù)據(jù)
 - CONUS :數(shù)據(jù)范圍為美國(CONtinental United States boundary)
 - monthly :數(shù)據(jù)的時(shí)間分辨率為月份
 
在xarray數(shù)據(jù)中,使用 .sel() 方法可以快速提取數(shù)據(jù)子集
# 根據(jù)經(jīng)緯度進(jìn)行取值 key=400 longitude = max_temp_xr["air_temperature"]["lon"].values[key] latitude = max_temp_xr["air_temperature"]["lat"].values[key]print("Long, Lat values:", longitude, latitude) Long, Lat values: 251.89422607421875 41.72947692871094在地圖上顯示選取點(diǎn)的位置
extent = [-120, -70, 24, 50.5] central_lon = np.mean(extent[:2]) central_lat = np.mean(extent[2:])f, ax = plt.subplots(figsize=(12, 6),subplot_kw={'projection': ccrs.AlbersEqualArea(central_lon, central_lat)}) ax.coastlines() # Plot the selected location ax.plot(longitude-360, latitude, '^', transform=ccrs.PlateCarree(),color="r", markersize=15)ax.set_extent(extent) ax.set(title="Location of the Latitude / Longitude Being Used To to Slice Your netcdf Climate Data File")# Adds continent boundaries to the map ax.add_feature(cfeature.LAND, edgecolor='black')ax.gridlines() plt.show()# 使用.sel()方法提取對(duì)應(yīng)經(jīng)緯度位置的數(shù)據(jù) one_point=max_temp_xr["air_temperature"].sel(lat=latitude,lon=longitude)one_point # 提取具體點(diǎn)位置的數(shù)據(jù)結(jié)果為該點(diǎn)的時(shí)間序列數(shù)據(jù) one_point.shape (672,) # 查看該點(diǎn)上的前五條數(shù)據(jù) one_point.values[:5] array([271.11615, 274.05585, 279.538 , 284.42365, 294.1337 ],dtype=float32) # 直接使用xarray直接繪制該點(diǎn)數(shù)據(jù)的時(shí)間序列折線圖 one_point.plot() plt.show()
# 使用matplotlib繪制統(tǒng)計(jì)圖 f, ax = plt.subplots(figsize=(12, 6)) one_point.plot.line(hue='lat',marker="o",ax=ax,color="grey",markerfacecolor="purple",markeredgecolor="purple") ax.set(title="Time Series For a Single Lat / Lon Location")# 導(dǎo)出為png格式 # plt.savefig("single_point_timeseries.png") plt.show()
將 xarray 數(shù)據(jù)轉(zhuǎn)換成 Pandas DataFrame 格式并導(dǎo)出為 csv 文件
# 轉(zhuǎn)換為DataFrame one_point_df = one_point.to_dataframe() # View just the first 5 rows of the data one_point_df.head()# pd導(dǎo)出為.csv文件 one_point_df.to_csv("one-location.csv")
根據(jù)時(shí)間和地點(diǎn)對(duì)數(shù)據(jù)進(jìn)行切片
start_date="2000-01-01" end_date="2005-01-01"temp_2000_2005=max_temp_xr['air_temperature'].sel(time=slice(start_date,end_date),lat=45.02109146118164,lon=243.01937866210938) temp_2000_2005查看切片得到的數(shù)據(jù)信息
temp_2000_2005.shape (60,)切片時(shí)間段內(nèi)的時(shí)間序列數(shù)據(jù)顯示
# Plot the data just like you did above f, ax = plt.subplots(figsize=(12, 6)) temp_2000_2005.plot.line(hue='lat',marker="o",ax=ax,color="grey",markerfacecolor="purple",markeredgecolor="purple") ax.set(title="A 5 Year Time Series of Temperature Data For A Single Location") plt.show()
對(duì)特定時(shí)間段以及指定的空間范圍內(nèi)的數(shù)據(jù)進(jìn)行切片
# 設(shè)定起始和結(jié)束時(shí)間 start_date = "1950-01-15" end_date = "1950-02-15"two_months_conus = max_temp_xr["air_temperature"].sel(time=slice(start_date, end_date)) # 查看切片后的數(shù)據(jù)信息 two_months_conus.shape (2, 585, 1386) # two_months_conus.plot() # plt.show()數(shù)據(jù)的空間可視化
# 使用xarray.plot()可以對(duì)數(shù)據(jù)進(jìn)行快速可視化 two_months_conus.plot(x="lon",y="lat",col="time", # 屬性值col_wrap=1) # 按列繪制 plt.suptitle("Two Time Steps of Monthly Average Temp", y=1.03) plt.show()two_months_conus.plot(x="lon",y="lat",col="time",col_wrap=2)# 按行繪制 plt.show()
# 使用matplotlib繪制地圖 central_lat = 37.5 central_long = 96 extent = [-120, -70, 20, 55.5] # CONUSmap_proj = ccrs.AlbersEqualArea(central_longitude=central_lon,central_latitude=central_lat)aspect = two_months_conus.shape[2] / two_months_conus.shape[1] p = two_months_conus.plot(transform=ccrs.PlateCarree(), # the data's projectioncol='time', col_wrap=1,aspect=aspect,figsize=(10, 10),subplot_kws={'projection': map_proj}) # the plot's projectionplt.suptitle("Two Time Steps of CONUS Historic Temperature Data", y=1) # Add the coastlines to each axis object and set extent for ax in p.axes.flat:ax.coastlines()ax.set_extent(extent) d:\ProgramData\Anaconda3\envs\pygis\lib\site-packages\xarray\plot\facetgrid.py:373: UserWarning: Tight layout not applied. The left and right margins cannot be made large enough to accommodate all axes decorations. self.fig.tight_layout()
將數(shù)據(jù)導(dǎo)出為Geotiff文件
- 使用 rioxarray 將數(shù)據(jù)導(dǎo)出為 geotiff文件格式
 
# 繪制數(shù)據(jù) two_months_tiff.plot(col="band") plt.show()
two_months_tiff.rio.nodata -9999.0 # 使用.where() to mask函數(shù)進(jìn)行掩膜 two_months_tiff = xr.open_rasterio(file_path)two_months_clean = two_months_tiff.where(two_months_tiff != two_months_tiff.rio.nodata)two_months_clean.plot(col="band") plt.show()
文章代碼:
https://gitee.com/jiangroubao/learning/blob/master/NetCDF4/
總結(jié)
以上是生活随笔為你收集整理的python中的.nc文件处理 | 03 指定位置的数据切片及可视化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: windows上安装detectron2
 - 下一篇: idea启动项目提示端口占用怎么办