处理数组形状
>>> import numpy as np >>> m = np.arange(24) >>> m array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]) >>> m.shape (24,) >>> n = m.reshape(3,8) >>> n array([[ 0, 1, 2, 3, 4, 5, 6, 7], [ 8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23]]) >>> o = m.reshape(3,2,4) >>> o array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 8, 9, 10, 11], [12, 13, 14, 15]], [[16, 17, 18, 19], [20, 21, 22, 23]]]) >>> m.shape #直接改变形状 (24,) >>> m array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]) >>> m.resize(3,8) #直接改变形状 >>> m array([[ 0, 1, 2, 3, 4, 5, 6, 7], [ 8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23]]) >>> m.transpose() #转置,视图 array([[ 0, 8, 16], [ 1, 9, 17], [ 2, 10, 18], [ 3, 11, 19], [ 4, 12, 20], [ 5, 13, 21], [ 6, 14, 22], [ 7, 15, 23]])
>>> #多维转一维 >>> e array([[[10, 11, 12, 13, 14], [ 0, 1, 2, 3, 4]], [[20, 22, 24, 26, 28], [ 0, 2, 4, 6, 8]]]) >>> e.ravel() array([10, 11, 12, 13, 14, 0, 1, 2, 3, 4, 20, 22, 24, 26, 28, 0, 2, 4, 6, 8]) >>> n.flatten() #重新分配内在 array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]) >>> n.shape(24,) Traceback (most recent call last): File "<pyshell#62>", line 1, in <module> n.shape(24,) TypeError: 'tuple' object is not callable >>> n array([[ 0, 1, 2, 3, 4, 5, 6, 7], [ 8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23]]) >>> n.resize(24,) >>> n array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23])