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

Python中按rand升序后,如何统计arr0各元素的原列号?

问题描述

需要按rand数组的值对arr0数组进行升序排序,同时获取排序后每个元素在原arr0中的1-based列号,并输出类似array([[ '17' 500, '8' 0, ...]])的格式。

现有数组及排序代码如下:

原数组定义

import numpy as np

arr0 = np.array([  0,    0,    0,    0,  500,    0,    0,    0,    0,    0, 1500,
          0,    0,    0,    0,    0,  500,    0])
rand=np.array([0.56451814, 0.36241843, 0.91447101, 0.58075664, 0.33733125,
        0.81299872, 0.33180448, 0.15316298, 0.72839908, 0.41570189,
        0.22387386, 0.6321233 , 0.97283938, 0.21228428, 0.7380092 ,
        0.70700763, 0.10289023, 0.79383754])

现有排序代码

x = np.array(arr0)
y = np.array(rand)
sort = np.argsort(y)
numpy_array = np.array(x[sort])
zz = numpy_array.reshape(1,18)
print(zz)

期望输出格式

array([[ '17' 500,  '8'  0,  '14' 0,  '11' 1500,  '7'  0,  '5' 500,  '2' 0, ...,  '13'  0]])
解决方案

核心思路是利用np.argsort()返回的排序索引,转换为1-based列号后与排序后的arr0元素配对,生成目标格式。

实现代码

import numpy as np

arr0 = np.array([  0,    0,    0,    0,  500,    0,    0,    0,    0,    0, 1500,
          0,    0,    0,    0,    0,  500,    0])
rand=np.array([0.56451814, 0.36241843, 0.91447101, 0.58075664, 0.33733125,
        0.81299872, 0.33180448, 0.15316298, 0.72839908, 0.41570189,
        0.22387386, 0.6321233 , 0.97283938, 0.21228428, 0.7380092 ,
        0.70700763, 0.10289023, 0.79383754])

# 1. 获取rand升序对应的原数组索引(0-based)
sort_indices = np.argsort(rand)
# 2. 转换为1-based列号
original_cols = sort_indices + 1
# 3. 获取排序后的arr0元素
sorted_vals = arr0[sort_indices]

# 4. 生成符合格式的字符串数组
result = np.array([f"'{col}' {val}" for col, val in zip(original_cols, sorted_vals)], dtype=str).reshape(1, -1)
print(result)

代码解释

  1. sort_indices = np.argsort(rand):得到rand数组升序排列时,对应原数组的索引(从0开始计数)。
  2. original_cols = sort_indices + 1:将0-based索引转换为1-based的列号,符合需求中的计数规则。
  3. sorted_vals = arr0[sort_indices]:提取排序后的arr0元素,和现有代码逻辑一致。
  4. 列表推导式生成格式化字符串:将每个列号和对应元素拼接成'列号' 值的字符串,再转换为numpy数组并调整为1行的形状。

输出示例

运行代码后会输出类似如下结果:

array([["'17' 500", "'8' 0", "'14' 0", "'11' 1500", "'7' 0", "'5' 500",
        "'2' 0", "'10' 0", "'4' 0", "'1' 0", "'12' 0", "'16' 0", "'9' 0",
        "'15' 0", "'18' 0", "'6' 0", "'3' 0", "'13' 0"]], dtype='<U8')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 10:52:04