numpy 常用api(二)

来源:互联网 发布:熟食店 知乎 编辑:程序博客网 时间:2024/05/29 18:24

多维数组的索引

>>> import numpy as np>>> a = np.zeros((3, 3, 3))>>> a[0, 0] = 1>>> aarray([[[ 1.,  1.,  1.],        [ 0.,  0.,  0.],        [ 0.,  0.,  0.]],       [[ 0.,  0.,  0.],        [ 0.,  0.,  0.],        [ 0.,  0.,  0.]],       [[ 0.,  0.,  0.],        [ 0.,  0.,  0.],        [ 0.,  0.,  0.]]])              # a[0, 0] == a[0, 0, :]
>>> a = np.zeros((3, 3, 3))>>> a[0] = 1                # a[0] == a[0, :, :]>>> aarray([[[ 1.,  1.,  1.],        [ 1.,  1.,  1.],        [ 1.,  1.,  1.]],       [[ 0.,  0.,  0.],        [ 0.,  0.,  0.],        [ 0.,  0.,  0.]],       [[ 0.,  0.,  0.],        [ 0.,  0.,  0.],        [ 0.,  0.,  0.]]])

random generator(RNG)

rng = np.random.RandomState(23455)

注意,这里的随机数生成器对象rng属于伪随机数生成器(pseudo-random number generator)。何谓伪随机数生成器,即是只要指定种子值(seed),按照一定的随机数生成原理,其后的值都是固定的。

>>> rng = np.random.RandomState(23455)>>> rng.randn(10)array([-0.40763092,  2.02315283,  1.50094199,  1.72905444, -1.03166787,       -0.63524931, -1.45931026, -2.0367523 , -1.09946837,  0.81414845])>>> rng2 = np.random.RandomState(23455)>>> rng2.randn(10)array([-0.40763092,  2.02315283,  1.50094199,  1.72905444, -1.03166787,       -0.63524931, -1.45931026, -2.0367523 , -1.09946837,  0.81414845])        # 与rng生成的一模一样

x.ndim == len(x.shape)

  • x.ndim是一个scalar

  • x.shape是一个tuple

np.ravel()

Return a contiguous flattened array(也即一位数组,其ndim==1).

矩阵->数组(按照指定的顺序),等价于reshape(-1, order=order)

>>> x = np.array([[1, 2, 3], [4, 5, 6]])>>> r.ravel()array([1, 2, 3, 4, 5, 6])>>> r.reshape(-1)

这又等价于matlab(最大的不同在于转换时的序):

% matlabX = magic(3)X(:)
X =   8   1   6   3   5   7   4   9   2ans =   8   3   4   1   5   9   6   7   2  

matlab默认以列序优先,且默认得到的是一个列向量。
在numpy中,我们也可以指定转换的顺序:

>>> x = np.array([[1, 2, 3], [4, 5, 6]])>>> x.ravel(order='F')array([1, 4, 2, 5, 3, 6])
1 0
原创粉丝点击