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

Numpy argsort按数值整体排序异常:当前仅按首字符排序

Fixing Numpy Array Sorting by Numeric Value Instead of String Lexicographical Order

The issue here is that your numpy array has a dtype of object (since it contains a mix of string and numeric values). When you sort using a[:, 2].argsort(), numpy falls back to comparing elements as strings using lexicographical order—this is why '31' gets placed before '5' (the character '3' has a lower ASCII value than '5').

Solution 1: Convert the Target Column to Numeric Type Before Sorting

The most straightforward fix is to explicitly convert the third column to an integer type, then use that to generate the sort indices:

import numpy as np
a = np.array([["value1", "value2", 3, "value4", "value5"], 
              ["value1", "value2", -10, "value4", "value5"], 
              ["value1", "value2", 31, "value4", "value5"], 
              ["value1", "value2", 5, "value4", "value5"], 
              ["value1", "value2", 3, "value4", "value5"]])

# Convert the 3rd column (index 2) to integers
numeric_col = a[:, 2].astype(int)
# Use the sorted indices of the numeric column to reorder the original array
a_sorted = a[numeric_col.argsort()]

print("Sorted:")
print(a_sorted)

Solution 2: Use a Key Function (Numpy 1.23+)

If you're using Numpy 1.23 or newer, you can use the key parameter directly in np.sort to specify that we should sort based on the numeric value of the third column:

a_sorted = np.sort(a, axis=0, key=lambda row: int(row[2]))
print("Sorted:")
print(a_sorted)

Why Changing 31 to 51 Worked

When you replaced 31 with 51, the string representation '51' has the same starting character as '5'. String comparison checks characters left-to-right: since '5' has no second character, it's considered "smaller" than '51', so 5 gets placed before 51—matching your expected numeric order. With '31', the first character '3' is smaller than '5', so it gets sorted before '5' incorrectly.

Both solutions above will produce your desired output:

Sorted:
[['value1' 'value2' '-10' 'value4' 'value5']
 ['value1' 'value2' '3' 'value4' 'value5']
 ['value1' 'value2' '3' 'value4' 'value5']
 ['value1' 'value2' '5' 'value4' 'value5']
 ['value1' 'value2' '31' 'value4' 'value5']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:16:30