Skip to main content
 首页 » 编程设计

python之numpy 数组 : basic questions

2024年10月24日7findumars

抱歉,这个问题太基础了

A=np.arange(64).reshape(2,32)

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, 24, 25, 26, 27, 28, 29, 30, 31], 
       [32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 
        49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63]]) 

A.reshape(4,4,4)

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], 
        [24, 25, 26, 27], 
        [28, 29, 30, 31]], 
 
       [[32, 33, 34, 35], 
        [36, 37, 38, 39], 
        [40, 41, 42, 43], 
        [44, 45, 46, 47]], 
 
       [[48, 49, 50, 51], 
        [52, 53, 54, 55], 
        [56, 57, 58, 59], 
        [60, 61, 62, 63]]]) 

现在,我希望像 A[2] 或 A[2,:] 或 A[2,:,:] 这样的东西返回矩阵

[[32, 33, 34, 35], 
 [36, 37, 38, 39], 
 [40, 41, 42, 43], 
 [44, 45, 46, 47]] 

和 A[2,2,2] 例如返回 42

但是我得到了这个错误

IndexError: too many indices for array 

请您参考如下方法:

你必须做

A = A.reshape(4,4,4) 

代替

A.reshape(4,4,4) 

因为reshape不是inplace,所以需要这样做。然后你可以做

A[2,2,2] 
Out[301]: 42