1 import numpy as np
%通过链表创建数组
1 mylist = [1, 2, 3] 2 x = np.array(mylist) 3 x
array([1, 2, 3])
%直接创建数组
1 y = np.array([4, 5, 6]) 2 y
array([4, 5, 6])
%创建多维数组
1 m = np.array([[7, 8, 9], [10, 11, 12]]) 2 m
array([[ 7, 8, 9], [10, 11, 12]])
1 m.shape
(2, 3)
1 n = np.arange(0, 30, 2) # start at 0 count up by 2, stop before 30 2 n
array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28])
1 n = n.reshape(3, 5) # reshape array to be 3x5 2 n
array([[ 0, 2, 4, 6, 8], [10, 12, 14, 16, 18], [20, 22, 24, 26, 28]])
1 o = np.linspace(0, 4, 9) # return 9 evenly spaced values from 0 to 4 2 o
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. ])
1 o.resize(3, 3) 2 o
array([[ 0. , 0.5, 1. ], [ 1.5, 2. , 2.5], [ 3. , 3.5, 4. ]])
1 np.ones((3, 2))
array([[ 1., 1.], [ 1., 1.], [ 1., 1.]])
1 np.zeros((2, 3))
array([[ 0., 0., 0.], [ 0., 0., 0.]])
1 np.eye(3)
array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]])
1 np.diag(y)
array([[4, 0, 0], [0, 5, 0], [0, 0, 6]])
1 np.array([1, 2, 3] * 3)
array([1, 2, 3, 1, 2, 3, 1, 2, 3])
1 np.repeat([1, 2, 3], 3)
array([1, 1, 1, 2, 2, 2, 3, 3, 3])
1 p = np.ones([2, 3], int) 2 p
array([[1, 1, 1], [1, 1, 1]])
1 np.vstack([p, 2*p])
array([[1, 1, 1], [1, 1, 1], [2, 2, 2], [2, 2, 2]])
1 np.hstack([p, 2*p])
array([[1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2]])