Python:Numpy学习

时间:2024-10-08 14:04:56
 import numpy as np
# 基础属性
array = np.array([[[1,2,3], [0,0,1]], [[1,2,3], [0,0,1]]],
dtype = np.int64) print(array)
print(array.ndim) # number of dim
print(array.shape) # shape
print(array.size) # number of elements
print(array.dtype) # 创建array
a = np.array([1,2,3,4]) # 1 dim b = np.array([[1,2,3,4]]) # row vector, 2 dim
c = np.array([[1], [2], [3] ,[4]]) # column vector, 2 dim
print(a.shape, b.shape, c.shape) a = np.zeros( (2,3), dtype = np.float)
a = np.ones( (2,3), dtype = np.float)
a = np.empty( (2,3), dtype = np.float)
a = np.arange(10, 20) # alike function range
a = np.linspace(1, 10, 5) # interval
print(a) # 基础运算(向量式运算)
'''向量'''
a = np.array([10, 20, 30, 40])
b = np.arange(4)
print( a + b)
print( a**2)
print( a < 20) '''矩阵'''
a = np.array([[1,1],
[0,1]])
b = np.arange(4).reshape((2,2))
print( a*b )
print( np.dot(a, b) ) # equal a.dot(b) print(np.argmax(a))
print(np.argmin(a)) A = np.arange(14, 2, -1).reshape((3,4))
print(np.clip(A, 5, 9)) '''随机数''' # module: np.random
a = np.random.random((2,4))
print(a)
print(np.sum(a, axis = 1))
print(np.min(a, axis = 0)) # 索引
'''一维array'''
A = np.arange(3, 15)
print(A[2])
print(A[0:5:2]) '''二维array'''
A = np.arange(3, 15).reshape(3, 4)
print(A[2])
print(A[2,:]) print(A[2][1])
print(A[2, 1]) # array合并
A = np.array([1,1,1])
B = np.array([2,2,2]) print(np.vstack((A,B))) # vertival stack
print(np.hstack((A,B))) # horizontal stack A[np.newaxis, :] # 1 * 3
A[:, np.newaxis] # 3 * 1 a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]]) # array分割
A = np.arange(12).reshape((3,4)) print(np.split(A, 2, axis = 1))
print(np.array_split(A, 3, axis = 1))
print(np.split(A, 3, axis = 0)) print(np.vsplit(A, 3))
print(np.hsplit(A, 2)) # copy and deep copy
a = np.array([1,2,3,10])
b = a
c = a
d = b b = a.copy()
a[3] = 44
print(a)
print(b)