如何在 xarray 中查找特定变量点的时间、纬度、经度索引

How to find index for time, lat, lon for particular variable point in xarray

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

我想隔离高于特定阈值的值和 return 每个值的索引。例如:

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

for x in outliers.tp:
    print(x)

当我遍历异常值时,它会为我提供每个 'tp' 值的信息,但我需要关联的索引。 例如,取 0.08361223 的一个 tp 值(在上图中)我想 return time_index(1981-03-01 的索引),lat_index(8.25 的索引) 和 lon_index(索引为 38.25)。 我是 netcdf 文件和 python 的新手,非常感谢任何指导。

你可以这样写:

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))

它不是很优雅,但很管用。