NumPy小技巧

本文记录写Python过程中用到的各种NumPy小技巧. (´・ω・`)

长期更新!

对某一维应用相同的函数

事实上,map也可以做到,但是我在class里用map的时候遇到了一点小问题,遂用NumPy.

1
np.apply_along_axis(function, axis, arr)

满足条件元素的下标

1
np.argwhere(conditions)

各种随机数的生成

1
2
3
4
5
6
7
8
9
# axb的数组,元素为[0, 1]之间均匀分布的随机样本
# 如果不指明数组大小,则返回一个随机数
np.random.rand(a, b)

# 数组元素符合标准正态分布N(0, 1)
np.random.randn(a, b)

# 数组元素为[low, high)之间离散均匀分布的整数
np.random.randint(low, high, size)

开一个与原矩阵形状相同的新矩阵

1
new = np.empty_like(original)

按索引列表赋值

设有矩阵a与索引列表idx

1
2
a = np.array([[1, 2, 3], [4, 5, 6]])
idx = np.array([[0,2], [1,2]])

想要达到如下效果:

1
2
3
4
for i in range(len(a)):
a[i, idx[i]] = 100

# a: np.array([[100, 2, 100], [4, 100, 100]])

那么可以这样做:

1
np.put_along_axis(a, idx, 100, axis=1)