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

Python二维数组排序:相同y值对应x坐标升序排列方法

NumPy 坐标排序实现方案

需求是保持y坐标原有排列顺序完全不变,仅对y值相同的坐标点对应的x坐标做升序排序,以下是可直接运行的实现:


方法1:适配y值连续成块的场景(和示例匹配)

示例中相同y值是连续出现的,用切分排序的方法效率最高:

import numpy as np

# 输入数据
x = [213,212,213,214,215,216,215,216,217,216,218,217,219,220,219]
y = [352,333,332,330,328,327,327,326,325,325,324,324,323,322,322]
xy = np.array([x, y])

# 找到y值发生变化的分界位置
split_pos = np.where(np.diff(xy[1]))[0] + 1
# 按分界切分x序列,每个分组内做升序排序后拼接
xy[0] = np.concatenate([np.sort(group) for group in np.split(xy[0], split_pos)])

运行后输出结果和期望完全一致:

x = [213, 212, 213, 214, 215, 215, 216, 216, 216, 217, 217, 218, 219, 219, 220]
y = [352, 333, 332, 330, 328, 327, 327, 326, 325, 325, 324, 324, 323, 322, 322]

方法2:通用场景(同y值可非连续出现)

如果相同y值可能散落在序列的不同位置,用分组排序的方法更稳妥,全程不会改动y数组的元素和顺序:

import numpy as np

x = np.array([213,212,213,214,215,216,215,216,217,216,218,217,219,220,219])
y = np.array([352,333,332,330,328,327,327,326,325,325,324,324,323,322,322])

# 遍历所有y的唯一值,对同y对应的x做升序重排
for val in np.unique(y):
    match_pos = np.where(y == val)[0]
    x[match_pos] = np.sort(x[match_pos])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 05:31:36