building
np.zeros((10,5))
np.ones((10,5))
arr[1:3,3:5].copy()
Attributes of arrays
x3 = np.random.randint(10, size=(3, 4, 5))
print("x3 ndim: ", x3.ndim)
print("x3 shape:", x3.shape)
print("x3 size: ", x3.size)
print("dtype:", x3.dtype)
print("itemsize:", x3.itemsize, "bytes")
print("nbytes:", x3.nbytes, "bytes")
Indexing of arrays
x3[2][4]
Slicing of arrays
x2[::-1, ::-1]
x2_sub_copy = x2[:2, :2].copy()
Reshaping of arrays
grid = np.arange(1, 10).reshape((3, 3))
Joining and splitting of arrays
x = np.array([1, 2, 3])
y = np.array([3, 2, 1])
np.concatenate([x, y]) #将0级元素合并
#array([1, 2, 3, 3, 2, 1])
grid = np.array([[1, 2, 3],[4, 5, 6]])
np.concatenate([grid, grid], axis=1) #将1级元素合并(去掉1级括号,并concatenate所有1级括号内的元素,组合成新的一级括号)
#array([[1, 2, 3, 1, 2, 3],[4, 5, 6, 4, 5, 6]])
np.vstack([x, grid]) #垂直append
np.hstack([grid, y]) #水平append
x = [1, 2, 3, 99, 99, 3, 2, 1]
x1, x2, x3 = np.split(x, [3, 5])
np.vsplit(grid, [2]) #[0:2]元素分为一组,[2:]分为一组
np.hsplit(grid,[1])
汇总统计
np.sum((inches > 0.5) & (inches < 1))
& np.bitwise_and
| np.bitwise_or
^ np.bitwise_xor
~ np.bitwise_not
x[x < 5]
np.sum()
np.mean() #平均数
np.std() #标准差
np.var() #方差
np.min() np.max()
np.argmin() np.argmax()
np.cumsum() #累积和
np.cumprod() #累计积
np.random
np.random.randn(100)
bool
arr.any()
arr.all()
sort
arr.sort(1) #按第一维排序
np.unique(arr) #不重复
np.intersect1d(x,y) #公共元素
np.union1d(x,y) #并集
np.in1d(x,y) #x元素是否包含于y
np.setdiff1d(x,y) #元素在x中不在y中
np.setxor1d(x,y) #xor
输入输出
np.save('example',arrbig)
np.load('example.npy') #.npy
存取txt
arr=np.loadtxt('array.txt',delimiter=',')
np.savetxt()
numpy.linalg func
np.dot(x,y)
from numpy.linalg import inv,qr
inv(arrbig) #矩阵的逆
q,r=qr(mat) #QR分解
diag dot trace det eig inv qr svd solve lstsq
np.identity(3) #3阶I
x,y=np.meshgrid(x,y)