首页 > 解决方案 > 如何为xarray中的特定变量点查找时间、纬度、经度的索引

问题描述

我将以下 netcdf 文件作为 xarray 数据集打开,其中包含每月的降水值。这是数据集(ds3)的样子:

在此处输入图像描述

我想隔离高于某个阈值的值并返回每个值的索引。例如:

outliers = ds3.where(ds3.tp > 0.08, drop=True)

for x in outliers.tp:
    print(x)

在此处输入图像描述

当我遍历异常值时,它会为我提供每个“tp”值的信息,但我需要相关的索引。例如,取一个 tp 值为 0.08361223(在上图中),我想返回 time_index(1981-03-01 的索引)、lat_index(8.25 的索引)和 lon_index(38.25 的索引)。我是 netcdf 文件和 python 的新手,希望得到任何指导。

标签: multidimensional-arrayindexingnetcdfpython-xarray

解决方案


你可以这样写:

ds3['tp'].where(ds3['tp'] > 0.08, drop=True).to_dataframe().dropna().reset_index()

它会为 pandas DataFrame 提供您想要的值及其相关坐标。为了关联整数索引,您可以编写:

df = ds3['tp'].where(ds3['tp'] > 0.08, drop=True).to_dataframe().dropna().reset_index()
for c in ds3.indexes:
    df[c] = df[c].apply(lambda v: list(ds3[c].values).index(v))

它不是很优雅,但很有效。


推荐阅读