numpy数组排序及其结构化数组头歌
时间: 2025-06-25 09:00:32 浏览: 13
### Numpy 数组排序方法
NumPy 提供了多种用于数组排序的功能。`numpy.sort()` 是最常用的函数之一,它可以沿指定轴对数组进行排序[^1]。
#### 基础排序
以下是 `numpy.sort()` 函数的一个简单例子:
```python
import numpy as np
arr = np.array([3, 1, 2])
sorted_arr = np.sort(arr)
print(sorted_arr) # 输出:[1 2 3]
```
此函数默认按升序排列,并返回一个新的已排序数组而不改变原始数组[^1]。
#### 沿不同轴排序
对于二维或多维数组,可以指定沿着哪个轴进行排序:
```python
arr_2d = np.array([[4, 2], [1, 3]])
sorted_along_axis0 = np.sort(arr_2d, axis=0)
sorted_along_axis1 = np.sort(arr_2d, axis=1)
print(sorted_along_axis0) # 输出:[[1 2] [4 3]]
print(sorted_along_axis1) # 输出:[[2 4] [1 3]]
```
如果希望展平整个数组后再排序,则可以通过设置参数 `axis=None` 实现:
```python
flattened_sorted = np.sort(arr_2d, axis=None)
print(flattened_sorted) # 输出:[1 2 3 4]
```
---
### 结构化数组详解
结构化数组允许定义具有复杂数据类型的数组,类似于数据库表中的记录。通过使用字段名称访问不同的列,这使得处理混合类型的数据更加方便[^3]。
#### 创建结构化数组
下面是一个创建和操作结构化数组的例子:
```python
dtype = [('name', 'U10'), ('age', int), ('height', float)]
structured_array = np.array([('Alice', 25, 1.75), ('Bob', 30, 1.8)], dtype=dtype)
print(structured_array['name']) # 输出:['Alice' 'Bob']
print(structured_array['age']) # 输出:[25 30]
print(structured_array['height']) # 输出:[1.75 1.8 ]
```
在此示例中,我们定义了一个包含三个字段 (`name`, `age`, 和 `height`) 的结构化数组。每个字段都有自己的数据类型[^2]。
#### 对结构化数组排序
要基于某个特定字段对结构化数组进行排序,可传递该字段名给 `order` 参数:
```python
sorted_by_age = np.sort(structured_array, order='age')
print(sorted_by_age[['name']]) # 输出:['Alice' 'Bob']
sorted_by_height_desc = structured_array[np.argsort(-structured_array['height'])]
print(sorted_by_height_desc[['name']]) # 输出:['Bob' 'Alice']
```
这里展示了两种方式来实现排序:一种是直接利用 `np.sort()` 并指定顺序;另一种则是借助于 `argsort()` 来获取索引位置再重新排列数组[^2]。
---
阅读全文
相关推荐


















