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

如何在NumPy结构化数组中为相同y值保留最小x值的x,y对?

NumPy结构化数组去重并保留最小x值的实现方法

原始代码与需求

你提供的结构化数组创建代码如下:

import numpy as np
arr1 = (np.array([2, 5, 8, 3, 10], dtype=np.int64),np.array([10, 10, 10, 8, 3], dtype=np.int64))

arr1_x = arr1[0]
arr1_y = arr1[1]

arr1_struct = np.empty(arr1_x.shape[0], dtype=[('x', int), ('y', int)])

arr1_struct["x"] = arr1_x
arr1_struct["y"] = arr1_y

需要完成的操作:

  • 检查是否存在重复的y值
  • 若存在重复y值,为每个y值仅保留一组(x,y)对
  • 保留的x值为该y值对应所有x中的最小值
  • 最终的(x,y)对需唯一无重复

预期结果:
保留的x,y对:

  • x=2,y=10
  • x=3,y=8
  • x=10,y=3

NumPy实现方法

可以通过排序+唯一值提取的方式高效实现需求,具体代码如下:

# 先按y值分组,再按x升序排序,确保每个y组内x最小的元素排在首位
sorted_arr = np.sort(arr1_struct, order=['y', 'x'])

# 提取唯一y值,并返回每个唯一值第一次出现的索引(对应x最小的元素)
_, unique_indices = np.unique(sorted_arr['y'], return_index=True)

# 根据索引获取最终结果
result = sorted_arr[unique_indices]

代码解释

  1. 排序:使用np.sort并指定order=['y', 'x'],先按y值将相同元素归为一组,再在每组内按x升序排列,确保每个y组里x最小的元素处于该组首位。
  2. 提取唯一元素:np.unique的return_index=True参数会返回每个唯一y值第一次出现的索引,这些索引对应的就是每个y组中x最小的元素。
  3. 获取结果:通过索引从排序后的数组中提取元素,得到符合要求的唯一(x,y)对。

运行代码后输出结果:

print(result)
# 输出:[(2, 10) (3, 8) (10, 3)]

另一种等价实现(使用lexsort)

也可以用np.lexsort完成排序,效果完全一致:

# 按x、y的优先级排序(先y后x升序)
sort_indices = np.lexsort((arr1_struct['x'], arr1_struct['y']))
sorted_arr = arr1_struct[sort_indices]

_, unique_indices = np.unique(sorted_arr['y'], return_index=True)
result = sorted_arr[unique_indices]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:45:31