12-numpy笔记-莫烦基本操作2
代码
import numpy as np A = np.arange(3,15) print('-1-') print(A) print('-2-') print(A[3]) A = np.arange(3,15).reshape((3,4)) print('-3-') print(A[1]) print('-4-') print(A[2][1]) # 第一行和第二行 print('-5-') print(A[1:3]) print('-6-') for row in A: print (row) print('-7-') for column in A.T: print (column) print('-8-') for item in A.flat: print (item) # 迭代器 print('-9-') print(A.flat) # 展成一行 print('-10-') print(A.flatten()) A = np.array([1,1,1]) B = np.array([2,2,2]) # 上下合并 print('-11-') print(np.vstack((A,B))) C = np.vstack((A,B)) print('-12-') print(A.shape, C.shape) # 左右合并 D = np.hstack((A,B)) print('-13-') print(D) print('-14-') print(A.shape, D.shape) #横向的数列转化到列,行向加维度 print('-15-') print(A[np.newaxis,:]) #纵向的数列转化到行,纵向的添加维度 print('-16-') print(A[:,np.newaxis]) A = np.array([1,1,1])[:,np.newaxis] B = np.array([2,2,2])[:,np.newaxis] # 三个向量的横向合并 print('-17-') print(np.hstack((A,A,B))) # 三个向量的竖向合并 C = np.concatenate((A,B,B,A)) print('-18-') print(C) # 三个向量的竖向合并 C = np.concatenate((A,B,B,A), axis=0) print('-19-') print(C) # 三个向量的横向合并 C = np.concatenate((A,B,B,A), axis=1) print('-20-') print(C) A = np.arange(12).reshape((3,4)) print('-21-') print(A) #分成两块,按列划分,只能进行相等的划分 print('-22-') print(np.split(A,2,axis = 1)) print('-23-') print(np.split(A,3,axis = 0)) #分成两块,按列划分,进行不相等的划分 print('-24-') print(np.array_split(A,3,axis = 1)) # 垂直划分 print('-25-') print(np.vsplit(A,3)) # 竖直划分 print('-26-') print(np.hsplit(A,2)) a=np.arange(4) b = a # 引用复制 c = a # abcd都是一样 d = a a[0] = 11 print('-27-') print(b,c,d) # 都是11 d is a e = a.copy() # deep copy
输出
-1- [ 3 4 5 6 7 8 9 10 11 12 13 14] -2- 6 -3- [ 7 8 9 10] -4- 12 -5- [[ 7 8 9 10] [11 12 13 14]] -6- [3 4 5 6] [ 7 8 9 10] [11 12 13 14] -7- [ 3 7 11] [ 4 8 12] [ 5 9 13] [ 6 10 14] -8- 3 4 5 6 7 8 9 10 11 12 13 14 -9- <numpy.flatiter object at 0x000002A6F47AB7B0> -10- [ 3 4 5 6 7 8 9 10 11 12 13 14] -11- [[1 1 1] [2 2 2]] -12- (3,) (2, 3) -13- [1 1 1 2 2 2] -14- (3,) (6,) -15- [[1 1 1]] -16- [[1] [1] [1]] -17- [[1 1 2] [1 1 2] [1 1 2]] -18- [[1] [1] [1] [2] [2] [2] [2] [2] [2] [1] [1] [1]] -19- [[1] [1] [1] [2] [2] [2] [2] [2] [2] [1] [1] [1]] -20- [[1 2 2 1] [1 2 2 1] [1 2 2 1]] -21- [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] -22- [array([[0, 1], [4, 5], [8, 9]]), array([[ 2, 3], [ 6, 7], [10, 11]])] -23- [array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8, 9, 10, 11]])] -24- [array([[0, 1], [4, 5], [8, 9]]), array([[ 2], [ 6], [10]]), array([[ 3], [ 7], [11]])] -25- [array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8, 9, 10, 11]])] -26- [array([[0, 1], [4, 5], [8, 9]]), array([[ 2, 3], [ 6, 7], [10, 11]])] -27- [11 1 2 3] [11 1 2 3] [11 1 2 3]