numpy基础用法 - Fri, Aug 21, 2020
numpy基础用法
import numpy as np
np.__version__
'1.19.1'
1. 基本类型
1.1 ndarray
a = np.array([1, 2, 3, 4, 5, 6])
print(type(a), a)
<class 'numpy.ndarray'> [1 2 3 4 5 6]
1.2 matrix
b = np.mat(a)
print(type(b), b)
<class 'numpy.matrix'> [[1 2 3 4 5 6]]
2. 初期化
2.1 array
n1array = np.array([1, 2, 3, 4, 5, 6]) # 一维
print(n1array.shape, n1array)
(6,) [1 2 3 4 5 6]
n2array = np.array([[1, 2, 3], [4, 5, 6]]) # 二维
print(n2array.shape, n2array)
(2, 3) [[1 2 3]
[4 5 6]]
2.2 zeros
n1zeros = np.zeros(6) # 一维
print(n1zeros.shape, n1zeros)
(6,) [0. 0. 0. 0. 0. 0.]
n2zeros = np.zeros((2,3)) # 二维
print(n2zeros.shape, n2zeros)
(2, 3) [[0. 0. 0.]
[0. 0. 0.]]
2.3 ones
n1ones = np.ones(6) # 一维
print(n1ones.shape, n1ones)
(6,) [1. 1. 1. 1. 1. 1.]
n2ones = np.ones((2,3)) # 二维
print(n2ones.shape, n2ones)
(2, 3) [[1. 1. 1.]
[1. 1. 1.]]
2.4 empty
n1empty = np.empty(6) # 一维
print(n1empty.shape, n1empty)
(6,) [0. 0. 0. 0. 0. 0.]
n2empty = np.empty((2,3)) # 二维
print(n2empty.shape, n2empty)
(2, 3) [[0. 0. 0.]
[0. 0. 0.]]
2.5 arange
n1arange = np.arange(6) # 一维
print(n1arange.shape, n1arange)
(6,) [0 1 2 3 4 5]
n2arange = np.arange(6).reshape(2,3) # 二维
print(n2arange.shape, n2arange)
(2, 3) [[0 1 2]
[3 4 5]]
2.6 linspace
n1linspace = np.linspace(0, 10, num=6) # 一维
print(n1linspace.shape, n1linspace)
(6,) [ 0. 2. 4. 6. 8. 10.]
n2linspace = np.linspace(0, 10, num=6).reshape(2,3) # 二维
print(n2linspace.shape, n2linspace)
(2, 3) [[ 0. 2. 4.]
[ 6. 8. 10.]]