You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取xArray中值为1的元素对应的坐标?

获取xArray中指定值的对应坐标

首先你的xArray实例定义如下:

import xarray as xr

test = xr.DataArray([[0,1], [1, 2]], dims=['x', 'y'], coords={'x': [5, 6], 'y': [-7, -8]})

方法一:利用xArray内置方法筛选

通过where方法筛选出值为1的元素,直接提取对应坐标:

# 筛选值为1的元素并保留坐标
target_elements = test.where(test == 1, drop=True)
# 组合x、y坐标为目标格式
result = [list(coord) for coord in zip(target_elements.x.values, target_elements.y.values)]
print(result)  # 输出: [[5, -8], [6, -7]]

方法二:结合Numpy索引映射坐标

先通过Numpy找到值为1的元素索引,再从坐标数组中提取对应值:

import numpy as np

# 获取值为1的元素的二维索引
indices = np.argwhere(test.values == 1)
# 根据索引匹配对应的x、y坐标
result = [[test.x.values[i], test.y.values[j]] for i, j in indices]
print(result)  # 输出: [[5, -8], [6, -7]]

内容的提问来源于stack exchange,提问作者clopen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 08:37:03