Python

xiaoxiao2021-02-28  38

基本运算

import numpy as np a = np.array([20,30,40,50]) b = np.arange(4) c = a - b #减法 d = b**2 #平方 e = 10 *np.sin(a) print(a<35) A = np.array([[1,1],[0,1]]) B = np.array([[2,0],[3,4]]) C = A*B #元素相乘 E = np.dot(A,B) #矩阵相乘 print(C) print(E)

import numpy as np a = np.ones((2,3),dtype = int) b = np.random.random((2,3)) print(a) print(b) b += a print(b) #a += b #error # Cannot cast ufunc add output from dtype('float64') to dtype('int32') with casting rule 'same_kind' print(a) print(a.sum()) print(a.min()) print(a.max()) c = np.arange(12).reshape(3,4) print(c) d = c.sum(axis=0) #sum of each column print(d) e = c.min(axis=1) # min of each row print(e) f = c.cumsum(axis=1) #cumulative sum along each row print(f)

输出

[[1 1 1] [1 1 1]] [[ 0.33554238 0.2963108 0.91907985] [ 0.86329755 0.21385802 0.98444173]] [[ 1.33554238 1.2963108 1.91907985] [ 1.86329755 1.21385802 1.98444173]] [[1 1 1] [1 1 1]] 6 1 1 [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [12 15 18 21] [0 4 8] [[ 0 1 3 6] [ 4 9 15 22] [ 8 17 27 38]]

通用函数ufunc

import numpy as np B = np.arange(3) print(B) print(np.exp(B)) print(np.sqrt(B)) C = np.array([2,1,3]) print(np.add(B,C))

索引、切片和迭代

a = np.arange(10)**3 print(a) print(a[2]) print(a[2:5]) a[:6:2] = -1000 print(a) print(a[: :-1]) def f(x,y): return 10*x+y b = np.fromfunction(f,(5,4),dtype= int) print(b) print(b[2,3]) print(b[0:5,1]) print(b[:,1]) print(b[1:3,:]) print(b[-1])

形状操作

import numpy as np #floor 计算各元素的floor值,即小于等于该值的最大正数 a = np.floor(10*np.random.random((3,4))) print(a) print(a.shape) # ravel flatten实现功能是一致的,将多维数组将为一维 #两者的区别在于ravel返回视图,会影响原始矩阵 #flatten 返回一份拷贝,对拷贝修改不影响原始矩阵 print(a.ravel()) print(a.flatten()) print(a.transpose()) #reshape 函数改变参数形状并返回它 #resize 函数改变数组自身 b = np.array([[7,5],[9,3],[7,2],[7,8],[6,8],[3,2]]) print(b) print(b.reshape(3,4)) b.resize((3,2)) print(b)

stack组合不同的数组

import numpy as np a = np.array([1,2,3]) print(a) b = np.array([4,5,6]) print(b) c = np.vstack((a,b)) print(c) d = np.hstack((a,b)) print(d) e = np.column_stack((a,b)) print(e)

输出

[1 2 3] [4 5 6] [[1 2 3] [4 5 6]] [1 2 3 4 5 6] [[1 4] [2 5] [3 6]]

将数组分割split成几个小数组

f = np.array([1,2,3,4,5,6,7,8,9,10,11,12]).reshape(2,6) print(f) print(np.hsplit(f,3)) #沿水平方向 print(np.vsplit(f,2)) #沿垂直方向

转载请注明原文地址: https://www.6miu.com/read-2625778.html

最新回复(0)