收藏本站 劰载中...网站公告 | 吾爱海洋论坛交流QQ群:835383472

[数据处理] 从nc文件中提取风速数据并且进行时间序列分析

[复制链接]
                                   本文目的
  • 介绍了如何从nc文件中,提取风速数据;
  • 介绍如何将风速数据转换成时间序列;
  • 简单的时间序列的趋势拆解(首发)。
    : t) p* J' W7 X1 u0 e
    2 U1 g, z3 L+ o) F. x
代码链接

代码我已经放在Github上面了,免费分享使用,https://github.com/yuanzhoulvpi2 ... ree/main/python_GIS

2 K0 g" Q+ e# r5 f5 w0 w& Y7 T

过程介绍

+ g7 L- o/ s# M% T
: F3 z! W6 N* P: V8 h( @, I' r

; s2 R4 F, ~* Q4 k5 d
1. 导入包: j* M' l. h2 {1 k7 g, K& d9 g
% F' t. x( M! O
[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

+ Z) \" E& l0 [0 S  r- ]% o+ b# V* ~* S0 G3 ?! g
6 m! w: J, ]/ J' X9 _( Q
2.导入数据 处理数据
% f- {3 m: B/ V6 h9 l/ n
5 }% W# f, }7 q
& c# G* ?! f% t' T- h% r" g4 g
[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]
7 g& B5 M6 `: ]8 f' R: p
4 c% |7 V$ j/ y- _* p4 A6 F7 j2 T
3. 计算风速数据
7 a+ y$ E* a  |, \* K* a: h
$ R" [8 O+ P7 l" z
- _- l6 f+ y7 a8 a; F8 n8 T8 a- p) k
[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

8 W7 L! E! _$ j: U2 X9 G+ o+ j# _
6b7fd110a68e6d3fd40460ccdd7a810b.png

5 x# y' D* u! Z/ a- r  _: w) q5 I. o- H/ Q
% ^7 J( d- z0 A$ \
4. 年度数据可视化
$ ?1 l9 e5 [. h: c! }  m
( @* ^+ s- U7 _6 Z
: X# f8 c! z' F4 x9 x/ \% Y
[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}$")
6 g0 l. b! n4 m
952d93a401a01cd1fa10be892b8b64d6.png

0 V+ D9 Z" e7 [$ q( _( n: m8 g) n! B" O1 o" `
4 _( h9 g  X) U$ _) q
5. 月维度数据可视化: U5 N/ _; u# E  m* v$ \6 O! h, x
[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")
1 ]; ^5 u5 ~  S% c. p/ u2 ~
a520cff3361647efbb668c89005a5570.png

1 y! m$ i) D* z& x
9 \" g4 H, Q# t3 Q* R

5 Z- Y: y3 y  R. m6.天维度数据可视化# z5 D' C( X! S( P  J6 a' ~4 X
  • 计算天数据4 o7 T  ~2 X# s) e9 C' \

    & }8 }# a$ F5 w) I
[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()
  • 可视化; y  O1 |/ s3 {

    5 r0 W* e8 c8 _+ a- J6 G
[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')

& ~, Q- Q5 \' ^8 C, b- F1 w# Z. B' h; y) O$ `" F
/ U/ G- f0 `% x
053571827f212c867e38f40c8aa49ca5.png

- V6 Q2 n# [! }, s: h5 k1.天维度数据做趋势拆解1 `4 q: ^* E& k2 y) J

1 S9 q  n% Q# F' S
[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')

  k. z1 ~7 O+ W" b( b. x" d
cd8468c3910ecbcfac542ed3328df432.jpeg                
& k3 |% g2 v, a/ f( X

$ c% A4 E: m5 G" o8 s
+ V1 q8 w) {8 B8 z  M5 I8 N8 ~1 ~9 j" S+ L. P! ]- |
7 Q8 a" n! a. b6 i& R
回复

举报 使用道具

相关帖子

全部回帖
暂无回帖,快来参与回复吧
懒得打字?点击右侧快捷回复 【吾爱海洋论坛发文有奖】
您需要登录后才可以回帖 登录 | 立即注册
尖叫的土豆
活跃在2026-3-23
快速回复 返回顶部 返回列表