numpy 的基本属性

array = np.array([[1,2,3],
                 [4,5,6]])
print(array)
print("number of dimation:",array.ndim) # 维度
print("shape : ",array.shape)
print("size:",array.size)

numpy 创建array

print("普通list",[1,2,3])
a = np.array([1,2,3],dtype=np.int64) # int32 float64 float32
print(a)
print(a.dtype)

b = np.array([[2,3,4],
              [5,6,7]])
print(b)

b = np.zeros((3,4))
print(b)
b = np.ones((3,4),dtype=np.int16)
print(b)
b = np.empty((3,4))
print(b)
b = np.arange(10,20,2) # 10到20步长2
print(b)
b = np.arange(12).reshape((3,4))
print(b)
b = np.linspace(1,10,5) # 生成线段等差数列
b_ = np.arange(1,10,5) # 10到20步长2
print(b)
print(b_)

基础的运算1

a = np.array([10,20,30,40])
b = np.arange(4)
print(a)
print(b)
print(a-b)
print(a+b)
print(a*b)
print(b**2) # 平方
print(np.sin(a)) # sin
print(np.cos(a)) # sin
print(b<3)

print("-----------------------------------------------")

a = np.array([[1,1],
              [0,1]])
b = np.arange(4).reshape((2,2))
print(a)
print(b)
print(a*b)
print(np.dot(a,b))
print(a.dot(b))

print("-----------------------------------------------")

a = np.random.random((2,4)) # 0~1随机数字
print(a)
print(np.sum(a))
print(np.min(a))
print(np.max(a))
print(np.sum(a,axis=1)) # axis=1 列中求和

numpy 基础的运算2

A = np.arange(14,2,-1).reshape((3,4))
print(A)
print(np.argmin(A)) # 最小值的索引
print(np.argmax(A)) # 最大值的索引
print(np.mean(A))
print(A.mean())
print(np.average(A))
print(np.median(A)) # 中位数
print("cumsum",np.cumsum(A)) # 累加
print("diff",np.diff(A)) # 累差
print("nonzero",np.nonzero(A)) # 累差
print("sort",np.sort(A)) # 累差
print(np.transpose(A))
print(A.T)
print((A.T).dot(A))
print(np.clip(A,5,9)) # 大于9的数字是9,小于5的是5
print(np.mean(A,axis=0))

numpy 索引

A = np.arange(3,15).reshape((3,4))
print(A)
print(A[2][1])
print(A[2,1])
print(A[2,:])
print(A[:,2])

for row in A:
    print(row)
print("----------------------------------------------")
for col in A.T:
    print(col)
    
print("----------------------------------------------")
print(A.flatten())

for item in A.flat:
    print(item)

array 合并

A = np.array([1,1,1])
B = np.array([2,2,2])

C = np.vstack((A,B))

print(A.shape)
print(C.shape)

C = np.hstack((A,B))
print("A.shape:\n",A.shape)
print("C.shape:\n",C.shape)
print("A.T:\n",A.T)
A = A[:,np.newaxis]
B = B[:,np.newaxis]
print("A:\n",A) # 在行上添加维度
print("B:\n",B) # 在列上添加维度
print("hstack\n",np.hstack((A,B)))

C = np.concatenate((A,B,B,A),axis=1)
print("concatenate:\n",C)

array 分割

A = np.arange(12).reshape((3,4))
print(A)
print("split:\n",np.split(A,3,axis=0))
print("array_split:\n",np.array_split(A,3,axis=1))
print("vsplit:\n",np.vsplit(A,3))
print("hsplit:\n",np.hsplit(A,2))

array copy 和 deep copy

a = np.arange(4)
b=a
a[0]=8
print("a:",a)
print("b:",b)
print("b is a:",b is a)
b = a.copy()
a[1:3] = [44,55]
print("a:",a)
print("b:",b)