xarray中是否有一个内置函数用于从数据集中删除异常值?

2024-04-28 20:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个时空.nc文件,作为xarray数据集打开,我想删除超过第99百分位的值。是否有任何简单/直接的方法来降低这些值

有关我的数据集的信息是

Dimensions:    (latitude: 204, longitude: 180, time: 985)
Coordinates:
  * longitude  (longitude) float32 -69.958336 -69.875 ... -55.124996 -55.04166
  * latitude   (latitude) float32 -38.041668 -38.12501 ... -54.87501 -54.95834
  * time       (time) datetime64[ns] 1997-09-06 1997-09-14 ... 2019-09-06
Data variables:
    chl        (time, latitude, longitude) float64 nan nan nan ... nan nan nan

Tags: 文件数据方法信息timenan时空dimensions
1条回答
网友
1楼 · 发布于 2024-04-28 20:25:03

您可以创建自己的函数

import xarray as xr
import numpy as np

# perc -> percentile that define the exclusion threshold 
# dim -> dimension to which apply the filtering

def replace_outliers(data, dim=0, perc=0.99):

  # calculate percentile 
  threshold = data[dim].quantile(perc)

  # find outliers and replace them with max among remaining values 
  mask = data[dim].where(abs(data[dim]) <= threshold)
  max_value = mask.max().values
  # .where replace outliers with nan
  mask = mask.fillna(max_value)
  print(mask)
  data[dim] = mask

  return data

测试

data = np.random.randint(1,5,[3, 3, 3])
# create outlier 
data[0,0,0] = 100

temp = xr.DataArray(data.copy())

print(temp[0])

输出:

array([[100,   1,   2],
       [  4,   4,   4],
       [  1,   4,   3]])

应用功能:

temp = replace_outliers(temp, dim=0, perc=99)
print(temp[0])

输出:

array([[[4, 1, 2],
        [4, 4, 4],
        [1, 4, 3]],

相关问题 更多 >