Python Numpy1
摘自:莫烦Python: mofanpy.com
numpy中矩阵属性:
ndim 维度个数
shape 形状
size 尺寸
ones全为1
zeros全为0
arange linspace
reshape 重新给定形状
import numpy as np
a = np.array([[1, 2, 3],[3, 4, 5]], dtype=np.int64)
print(a)
print(a.dtype)
a1 = np.zeros(24).reshape((4, 6))
print(a1)
a1 = np.zeros(24, dtype=np.int32).reshape((3, 8))
print(a1)
a2 = np.arange(10, 30, 2).reshape((2, 5))
print(a2)
a3 = np.linspace(10, 30, 2)
print(a3)
运行:
[[1 2 3]
[3 4 5]]
int64
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]]
[[10 12 14 16 18]
[20 22 24 26 28]]
[10. 30.]
‘+’ ‘-’ ‘*’ '/'对应位置的加减乘除
‘**’次方
dot矩阵乘法
np.random.random()随机数
sum求和
min求最小
max求最大
axis = 0每一列
axis = 1每一行
import numpy as np
a1 = np.arange(4).reshape((2, 2))
a2 = 5 - np.arange(4).reshape((2, 2))
print(a1)
print(a2)
print()
print(a1 + a2)
print(a1 - a2)
print()
print(a1**2)
print(a1 * a2)
print(a1.dot(a2))
print()
a = np.random.random((3, 4))
print(a)
print(a.sum())
print(np.sum(a))
print(np.min(a, axis=0))
运行:
[[0 1]
[2 3]]
[[5 4]
[3 2]]
[[5 5]
[5 5]]
[[-5 -3]
[-1 1]]
[[0 1]
[4 9]]
[[0 4]
[6 6]]
[[ 3 2]
[19 14]]
[[0.9869835 0.72223784 0.8831175 0.55571105]
[0.02412822 0.95441889 0.72040881 0.19416821]
[0.02349831 0.01261253 0.92007141 0.606019 ]]
6.603375270959382
6.603375270959382
[0.02349831 0.01261253 0.72040881 0.19416821]
索引
import numpy as np
a1 = np.arange(6).reshape((2, 3))
print(a1)
print(a1[1])
print(a1[1][1])
print(a1[1][:])
print(a1[1][0:2])
for row in a1:
print(row)
print(a1.flatten()) #转变为一行的array
for item in a1.flat: #返回一个迭代器
print(item)
运行:
[[0 1 2]
[3 4 5]]
[3 4 5]
4
[3 4 5]
[3 4]
[0 1 2]
[3 4 5]
[0 1 2 3 4 5]
0
1
2
3
4
5
合并
np.vstack
np.hstack
np.concatenate(, axis) 通过axis控制列或者行合并
import numpy as np
a = np.array([1, 1, 1])
b = np.array([2, 2, 2])
print(a)
print(a.T)
print(b)
c = np.vstack((a, b))
d = np.hstack((a, b))
print(c)
print(d)
# 序列转置后还是序列,不是矩阵
print()
print(a[np.newaxis, :]) # 在行上加了一个维度
print(a[np.newaxis, :].shape)
print()
print(a[:, np.newaxis]) # 在列上加了一个维度
print(a[:, np.newaxis].shape)
运行:
[1 1 1]
[1 1 1]
[2 2 2]
[[1 1 1]
[2 2 2]]
[1 1 1 2 2 2]
[[1 1 1]]
(1, 3)
[[1]
[1]
[1]]
(3, 1)
分割
np.vsplit
np.hsplit
np.split
import numpy as np
a = np.arange(24).reshape((4, 6))
print(np.split(a, 2, axis=0))
print(np.split(a, 3, axis=1)) # 不能进行不等的分割,使用array_split可以进行不等分割
运行:
[array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]]), array([[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])]
[array([[ 0, 1],
[ 6, 7],
[12, 13],
[18, 19]]), array([[ 2, 3],
[ 8, 9],
[14, 15],
[20, 21]]), array([[ 4, 5],
[10, 11],
[16, 17],
[22, 23]])]
浅复制 a=b
深复制 a=b.copy()