本文目的- 介绍了如何从nc文件中,提取风速数据;
- 介绍如何将风速数据转换成时间序列;
- 简单的时间序列的趋势拆解(首发)。/ P* t6 S- O- r! \& J3 G' b: S
1 p* |5 J* X! u' S* W: ~* u/ ]7 b) I
代码链接代码我已经放在Github上面了,免费分享使用,https://github.com/yuanzhoulvpi2 ... ree/main/python_GIS。 3 G( a; r1 {$ J7 e2 h
过程介绍
$ G% |: v( P! }1 P* B0 j; ?( m, b/ x" N$ w5 Q _
3 A2 C( [7 V' ^) p8 E5 k7 N6 d1. 导入包
/ p% i0 i( n% V+ D9 s: A0 a, n" O4 u
$ I( D5 A: T+ l! m[Python] 纯文本查看 复制代码 # 基础的数据处理工具
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt # 可视化
import datetime # 处理python时间函数
import netCDF4 as nc # 处理nc数据
from netCDF4 import num2date # 处理nc数据
import geopandas as gpd # 处理网格数据,shp之类的
import rasterio # 处理tiff文件
from shapely.geometry import Point # gis的一些逻辑判断
from cartopy import crs as ccrs # 设置投影坐标系等
from tqdm import tqdm # 打印进度条
from joblib import Parallel, delayed # 并行
import platform # 检测系统
tqdm.pandas()
# matplotlib 显示中文的问题
if platform.system() == 'Darwin':
plt.rcParams["font.family"] = 'Arial Unicode MS'
elif platform.system() == 'Windows':
plt.rcParams["font.family"] = 'SimHei'
else:
pass f8 @$ C; u% t) e# N
' r1 A. p& k# m# Z- O6 M* n# I% g- J; i4 \( S, |: i$ O
2.导入数据 处理数据0 m( }2 g2 f ]
# I9 P* y- s e' S. S
% H$ V; B5 t/ C0 p+ O; N& i
[Python] 纯文本查看 复制代码 # 导入数据
nc_data = nc.Dataset("./数据集/GIS实践3/2016_2020.nc")
# 处理数据
raw_latitude = np.array(nc_data.variables['latitude'])
raw_longitude = np.array(nc_data.variables['longitude'])
raw_time = np.array(nc_data.variables['time'])
raw_u10 = np.array(nc_data.variables['u10'])
raw_v10 = np.array(nc_data.variables['v10'])
# 提取缺失值,并且将缺失值替换
missing_u10_value = nc_data.variables['u10'].missing_value
missing_v10_value = nc_data.variables['v10'].missing_value
raw_v10[raw_v10 == missing_v10_value] = np.nan
raw_u10[raw_u10 == missing_u10_value] = np.nan
# 处理时间
def cftime2datetime(cftime, units, format='%Y-%m-%d %H:%M:%S'):
"""
将nc文件里面的时间格式 从cftime 转换到 datetime格式
:param cftime:
:param units:
:param format:
:return:
"""
return datetime.datetime.strptime(num2date(times=cftime, units=units).strftime(format), format)
clean_time_data = pd.Series([cftime2datetime(i, units=str(nc_data.variables['time'].units)) for i in tqdm(raw_time)])
clean_time_data[:4] ) w8 ~: E* r/ Z; k$ c' i; F
8 W( T8 i3 D R9 O7 t3. 计算风速数据
/ ?% {6 v8 c8 H$ Y8 P
& |& _! n$ r( D4 O3 S/ E
3 N* Q5 q2 Z/ V& R) z1 R[Python] 纯文本查看 复制代码 windspeed_mean = pd.Series([np.sqrt(raw_v10[i,:, :] ** 2 + raw_u10[i, :, :]**2).mean() for i in tqdm(range(clean_time_data.shape[0]))])
time_windspeed = pd.DataFrame({'time':clean_time_data,'mean_ws':windspeed_mean})
time_windspeed
9 ~# G; M7 l( K* V, v4 O2 K" N6 e( o- D1 Z+ s" S6 o9 J; V3 M$ X# Q
. e( t* [, q9 s2 a! M7 o
( L$ `8 ?! d/ q6 k% |9 F$ L5 P4. 年度数据可视化
$ v' @0 M5 N5 v8 U
6 \. ~$ R3 W! [, c+ G
+ {4 ^* |, I1 O5 }! K[Python] 纯文本查看 复制代码 year_data = time_windspeed.groupby(time_windspeed.time.dt.year).agg(
mean_ws = ('mean_ws', 'mean')
).reset_index()
# year_data
with plt.style.context('fivethirtyeight') as style:
fig, ax = plt.subplots(figsize=(10,3), dpi=300)
ax.plot(year_data['time'], year_data['mean_ws'], '-o',linewidth=3, ms=6)
ax.set_xticks(year_data['time'])
#
#
for i in range(year_data.shape[0]):
ax.text(year_data.iloc[/size][/font][i][font=新宋体][size=3]['time']+0.1, year_data.iloc[/size][/font][i][font=新宋体][size=3]['mean_ws'], str(np.around(year_data.iloc[/size][/font][i][font=新宋体][size=3]['mean_ws'], 2)),
bbox=dict(boxstyle='round', facecolor='white', alpha=0.5))
#
for i in ['top', 'right']:
ax.spines[/size][/font][i][font=新宋体][size=3].set_visible(False)
ax.set_title("各年平均风速")
ax.set_ylabel("$Wind Speed / m.s^{-1}$")
& R6 Z# Z, i9 @, N, B
9 M8 O$ b0 C U, ~# k- s4 N
- @3 |& y( z, _7 {% `
. p+ C5 Q6 H; N6 u6 D B5. 月维度数据可视化
3 @7 y/ [8 l) U3 m3 {! ?+ t[Python] 纯文本查看 复制代码 month_data = time_windspeed.groupby(time_windspeed.time.dt.month).agg(
mean_ws = ('mean_ws', 'mean')
).reset_index()
with plt.style.context('fivethirtyeight') as style:
fig, ax = plt.subplots(figsize=(10,3), dpi=300)
ax.plot(month_data['time'], month_data['mean_ws'], '-o',linewidth=3, ms=6)
ax.set_xticks(month_data['time'])
_ = ax.set_xticklabels(labels=[f'{i}月' for i in month_data['time']])
for i in range(month_data.shape[0]):
ax.text(month_data.iloc[/size][/font][i][font=新宋体][size=3]['time'], month_data.iloc[/size][/font][i][font=新宋体][size=3]['mean_ws']+0.05, str(np.around(month_data.iloc[/size][/font][i][font=新宋体][size=3]['mean_ws'], 2)),
bbox=dict(boxstyle='round', facecolor='white', alpha=0.5))
for i in ['top', 'right']:
ax.spines[/size][/font][i][font=新宋体][size=3].set_visible(False)
ax.set_title("各月平均风速")
ax.set_ylabel("$Wind Speed / m.s^{-1}$")
fig.savefig("month_plot.png") & N9 K3 O- ?7 P' c) d$ b
) A/ ~/ K Y9 d; a0 D3 D% o2 E
! o! v0 }; `1 V1 U [: i9 x: G 7 D# [& x& B5 {- Q1 q& y
6.天维度数据可视化
: I) D' x, w6 H4 J2 n- 计算天数据
, }5 Q! y( E. y6 k+ D9 p# p
f$ B" ~& Z9 v" g5 E9 y
[Python] 纯文本查看 复制代码 day_data = time_windspeed.groupby(time_windspeed.time.apply(lambda x: x.strftime('%Y-%m-%d'))).agg(
mean_ws = ('mean_ws', 'mean')
).reset_index()
day_data['time'] = pd.to_datetime(day_data['time'])
day_data = day_data.set_index('time')
day_data.head()- 可视化
- p9 `" {/ p/ Y5 |
+ m) _: ^6 _1 ^" V& K
[Python] 纯文本查看 复制代码 # day_data.dtypes
fig, ax = plt.subplots(figsize=(20,4), dpi=300)
ax.plot(day_data.index, day_data['mean_ws'], '-o')
# ax.xaxis.set_ticks_position('none')
# ax.tick_params(axis="x", labelbottom=False)
ax.set_title("每天平均风速")
ax.set_ylabel("$Wind Speed / m.s^{-1}$")
ax.set_xlabel("date")
fig.savefig('day_plot.png') 4 M; e. x* k4 v+ B
6 E: U) E2 [9 H6 Q# H9 N% o* L2 A* S( p# c- i
g4 ?2 }* g* ^; O3 G+ \% F+ d1.天维度数据做趋势拆解3 I9 H: Z- ?/ o4 \
0 C% H* j+ \* w) u3 e# y
[Python] 纯文本查看 复制代码 # 导入包
from statsmodels.tsa.seasonal import seasonal_decompose
from dateutil.parser import parse
# 乘法模型
result_mul = seasonal_decompose(day_data['mean_ws'], model="multilicative", extrapolate_trend='freq')
result_add = seasonal_decompose(day_data['mean_ws'], model="additive", extrapolate_trend='freq')
font = {'family': 'serif',
'color': 'darkred',
'weight': 'normal',
'size': 16,
}
# 画图
with plt.style.context('classic'):
fig, ax = plt.subplots(ncols=2, nrows=4, figsize=(22, 15), sharex=True, dpi=300)
def plot_decompose(result, ax, index, title, fontdict=font):
ax[0, index].set_title(title, fontdict=fontdict)
result.observed.plot(ax=ax[0, index])
ax[0, index].set_ylabel("Observed")
result.trend.plot(ax=ax[1, index])
ax[1, index].set_ylabel("Trend")
result.seasonal.plot(ax=ax[2, index])
ax[2, index].set_ylabel("Seasonal")
result.resid.plot(ax=ax[3, index])
ax[3, index].set_ylabel("Resid")
plot_decompose(result=result_add, ax=ax, index=0, title="Additive Decompose", fontdict=font)
plot_decompose(result=result_mul, ax=ax, index=1, title="Multiplicative Decompose", fontdict=font)
fig.savefig('decompose.png')
/ X. |& r! c: s1 s
0 e2 G6 K f' p: M
" H9 G3 O; j! g- Y
, M" T }2 M% s" S# C1 i8 s- P
* I4 p2 H" G# G t6 J( W: {& C" R
/ p( M8 k6 \+ N5 |' V2 {3 k
|