>

LoeiJe

:D 获取中...

何以解忧?唯有暴富

numpy学习笔记

numpy学习笔记

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 2019-10-25
# numpy 学习笔记
# icenaive
# 参考: https://github.com/lijin-THU/notes-python
# 仅供个人学习使用
#
# 6. 数组排序

import numpy as np

names = np.array(['bob', 'sue', 'jan', 'ad'])
weights = np.array([20.8, 93.2, 53.4, 61.8])
# 返回结果从小到大排
print(np.sort(weights))

# argsort函数
# 返回从小到大的排列在数组中的索引位置
ordered_indices = np.argsort(weights)
print(ordered_indices)

# 可以用它来进行索引
print(weights[ordered_indices])
print(names[ordered_indices])
# 使用函数并不会改变原来数组的值
print(weights)

# sort 和 argsort 方法
# 数组也支持方法操作
data = np.array([20.8, 93.2, 53.4, 61.8])
print(data.argsort())
print(data)
# argsort 方法与 argsort 函数的使用没什么区别,也不会改变数组的值。
# 但是sort方法会改变数组的值
data.sort()
print(data)

# 二维数组排序
# 对于多维数组, sort方法默认沿着最后一维开始排序
a = np.array([
[.2, .1, .5],
[.4, .8, .3],
[.9, .6, .7]
])
print(a)

print(np.sort(a))
# 改变轴 对每一列进行排序
print(np.sort(a, axis = 0))

# searchsorted函数
# searchsorted(sorted_array, valures)
# searchsorted 接受两个参数,其中,第一个必须是已经排序的数组

sorted_array = np.linspace(0, 1, 5)
values = np.array([.1, .8, .3, .12, .5, .25])

print(np.searchsorted(sorted_array, values))

排序数组:

0 1 2 3 4
0.0 0.25 0.5 0.75 1.0

数值:

0.1 0.8 0.3 0.12 0.5 0.25
插入位置 1 4 2 1 2 1

searchsorted 返回的值相当于保持第一个数组的排序性质不变,将第二个数组中的值插入第一个数组中的位置:

例如 0.1 在[0.0, 0.25) 之间,所以插入时应当放在第一个数组的索引 1 处,故第一个返回值为 1

1
2
3
4
5
6
7
8
9
10
11
data = np.random.rand(100)
data.sort()

# 不加括号默认为元组
bounds = .4, .6
print(bounds)

# 返回两个值的对应插入位置
low_idx, high_idx = np.searchsorted(data, bounds)
# 利用插入位置 可以将数组中元素提取出来
print(data[low_idx:high_idx])