【问题标题】:Sum a daily time series into a monthly time series with a NaN value threshold将每日时间序列求和为具有 NaN 值阈值的每月时间序列
【发布时间】:2018-07-15 18:35:54
【问题描述】:

我有一个从 1979 年 1 月 1 日到 2005 年 12 月 31 日的 3D 时间序列数据矩阵。该矩阵目前为 9862x360x720(日降雨量 x 0.5° 纬度 x 0.5° 经度)。我想将每日降雨量与每月降雨量相加(总共 324 个月),同时还设置一个对 NaN 值求和的阈值。

换句话说,如果特定纬度/经度网格单元格的每日 NaN 值超过 10 个,我想将每月总和单元格标记为 NaN。如果网格单元的每日 NaN 值少于 10 个,我想将剩余的非 NaN 每日值相加并将其用作每月值。

我成功地使用了 xarray 库的“重采样”函数,但我无法找到为 NaN 值设置阈值的方法。我读过的所有内容都说使用 sum 或 nansum 函数,但我找不到通过其中任何一个函数设置 NaN 阈值的方法。目前我对任何方法都持开放态度(xarray 或其他)。

import netCDF4
import numpy as np
import xarray as xr
import pandas as pd

f = netCDF4.Dataset("daily_data", 'r')

daily_dataset = xr.Dataset({'precipitation': (['time', 'lat', 'lon'],  f['precipitation'][:, :, :])},
             coords={'lat': (f['lat'][:]), 'lon': (f['lon'][:]), 'time': pd.date_range('1979-01-01', periods=9862)})

monthly_dataset = daily_dataset['precipitation'].resample('M', dim='time', how='sum', skipna=False)

我能够使用上述代码将每日数据汇总到每月,但我无法设置 NaN 阈值。每日数据当前存储在 NetCDF 文件中。

【问题讨论】:

  • 欢迎来到 SO。请提供minimal reproducible example。您当前尝试的代码会有所帮助。
  • 所以你需要一个函数,它需要一个迭代来总结和一个 nans 的阈值?

标签: python sum nan threshold xarray


【解决方案1】:

我相信这是你想要的:

NaN = float("nan") # Make a constant for NaN

def sum_nan_threshold(iterable, *, nan_threshold=10):
    if sum(x == NaN for x in iterable) >= nan_threshold: # Are there more NaNs then threshold?
        return NaN
    else:
        return sum(x for x in iterable if x != NaN) # Else sum up if not equal to NaN

【讨论】:

    猜你喜欢
    • 2018-06-23
    • 2021-02-13
    • 2019-05-12
    • 2021-05-17
    • 2020-05-10
    • 2021-05-21
    • 2019-06-05
    • 1970-01-01
    • 2020-04-10
    相关资源
    最近更新 更多