1 numpy属性
import numpy as np
array = np.array([
[1, 2, 3],
[2, 3, 4]
])
print(array)
print('number of dimension:', array.ndim) # 矩阵的维度
print('shape:', array.shape) # 矩阵的形状,几行几列
print('size:', array.size) # 矩阵的尺寸,几个元素
输出:
[[1 2 3]
[2 3 4]]
number of dimension: 2
shape: (2, 3)
size: 6
2 numpy 的创建 array
import numpy as np
a = np.array([2, 3, 4], dtype = np.int)
print(a)
print(a.dtype)
输出:
[2 3 4]
int32
创建全为0的矩阵:
import numpy as np
a = np.zeros((3, 3)) # 矩阵的形状3*3要用括号括起来
print(a)
输出:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
创建全为1的矩阵:
import numpy as np
a = np.ones((3, 3)) # 矩阵的形状3*3要用括号括起来
print(a)
输出:
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
什么都没有的矩阵:
import numpy as np
a = np.empty((3, 3)) # 矩阵的形状3*3要用括号括起来
print(a)
输出:
[[0.00000000e+000 0.00000000e+000 0.00000000e+000]
[0.00000000e+000 0.00000000e+000 1.87744945e-321]
[8.01097888e-307 2.14321575e-312 1.00000000e-002]]
.arange()和.reshape()
import numpy as np
a = np.arange(12).reshape((3, 4)) # 生成0到11的数,并将形状改为3*4
print(a)
输出:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
.linspace()
import numpy as np
a = np.linspace(1, 10, 5)
print(a)
输出:
[ 1. 3.25 5.5 7.75 10. ]
3 numpy的基础运算
减法
import numpy as np
a = np.array([10, 20, 30, 40])
b = np.arange(4)
print('a:', a)
print('b:', b)
print(a - b) # 对应元素一次相减
输出:
a: [10 20 30 40]
b: [0 1 2 3]
[10 19 28 37]
加法
import numpy as np
a = np.array([10, 20, 30, 40])
b = np.arange(4)
print('a:', a)
print('b:', b)
print(a + b) # 对应元素依次相加
输出:
a: [10 20 30 40]
b: [0 1 2 3]
[10 21 32 43]
三角运算:
import numpy as np
a = np.array([10, 20, 30, 40])
b = np.arange(4)
c = 10 * np.sin(a)
print('c:', c)
输出:
c: [-5.44021111 9.12945251 -9.88031624 7.4511316 ]
import numpy as np
a = np.array([10, 20,