import numpy as np
a = np.array([[1,2,3],
[2,3,4]])
print(a)
运行结果为:
[[1 2 3]
[2 3 4]]
b = np.zeros((3,4))
print(b)
运行结果为:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
c = np.ones((3,4))
print(c)
运行结果为:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
d = np.empty((3,4))
print(d)
运行结果为:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
e = np.arange(10,20,2)
print(e)
运行结果为:
[10 12 14 16 18]
f = np.arange(12).reshape((3,4))
print(f)
运行结果为:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
g = np.linspace(1,10,5)
print(g)
运行结果为:
[ 1. 3.25 5.5 7.75 10. ]
# 生成长度为5,在[0,1)之间平均分布的随机矩阵
h = np.random.random(size=5) 或 h = np.random.random((5,))
print(h)
运行结果为:
[0.41531148 0.53401601 0.7455592 0.69346509 0.03288469]
import numpy as np
a = np.array([[1,2,3,4,5,6]]).reshape(2,-1)
print(a)
运行结果为:
[[1 2 3]
[4 5 6]]
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
print(np.vstack((a,b)))
运行结果为:
[[1 2 3]
[4 5 6]]
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
print(np.hstack((a,b)))
运行结果为:
[1 2 3 4 5 6]
将序列变为有维度的矩阵
利用[:,np.newaxis]或[np.newaxis,:]
import numpy as np
a = np.array([1,2,3])
print(a)
a = np.array([1,2,3])[:,np.newaxis]
print(a)
a = np.array([1,2,3])[np.newaxis,:]
print(a)
运行结果为:
[1 2 3]
[[1]
[2]
[3]]
[[1 2 3]]
import numpy as np
a = np.array([1,1,1])[:,np.newaxis]
print(a)
b = np.array([2,2,2])[:,np.newaxis]
print(b)
c = np.concatenate((a,b,b,a),axis=1)
print(c)
运行结果为:
[[1]
[1]
[1]]
[[2]
[2]
[2]]
[[1 2 2 1]
[1 2 2 1]
[1 2 2 1]]
import numpy as np
a = np.arange(12).reshape(3,4)
print(a)
print(np.split(a,2,axis=1))
运行结果为:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[array([[0, 1],
[4, 5],
[8, 9]]), array([[ 2, 3],
[ 6, 7],
[10, 11]])]
import numpy as np
a = np.arange(12).reshape(3,4)
print(a)
print(np.array_split(a,3,axis=1))
运行结果为:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[array([[0, 1],
[4, 5],
[8, 9]]), array([[ 2],
[ 6],
[10]]), array([[ 3],
[ 7],
[11]])]
import numpy as np
a = np.arange(12).reshape(3,4)
print(a)
print(np.vsplit(a,3))
print(np.hsplit(a,2))
运行结果为:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8, 9, 10, 11]])]
[array([[0, 1],
[4, 5],
[8, 9]]), array([[ 2, 3],
[ 6, 7],
[10, 11]])]
import numpy as np
a = np.arange(4)
print(a)
b = a
b[0] = 100
print(b)
print(a)
运行结果为:
[0 1 2 3]
[100 1 2 3]
[100 1 2 3]
采用copy()函数
import numpy as np
a = np.arange(4)
print(a)
b = a.copy()
b[0] = 100
print(b)
print(a)
运行结果为:
[0 1 2 3]
[100 1 2 3]
[0 1 2 3]