Parameters: | indices : array_like An integer array whose elements are indices into the flattened version of an array of dimensions dims. Before version 1.6.0, this function accepted just one index value. dims : tuple of ints The shape of the array to use for unraveling indices. order : {‘C’, ‘F’}, optional Determines whether the indices should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order. New in version 1.6.0. |
Returns: | unraveled_coords : tuple of ndarray Each array in the tuple has the same shape as the indices array. |
numpy.unravel_index 說明
官網的api說明如下:
numpy.unravel_index(indices, dims, order='C')
Converts a flat index or array of flat indices into a tuple of coordinate arrays.
See also
Examples
>>>
>>>
np.unravel_index([22,
41,
37], (7,6))
(array([3, 6, 6]), array([4, 5, 1]))
>>>
np.unravel_index([31,
41,
13], (7,6),
order='F')
(array([3, 6, 6]), array([4, 5, 1]))
>>>
>>>
np.unravel_index(1621,
(6,7,8,9))(3,
1, 4, 1)
例子:
Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element ?
>>>
print np.unravel_index(100,(6,7,8))
(1,
5,
4)
解釋:
給定一個矩陣,shape=(6,7,8),即3維的矩陣,求第n個元素的下標是什麼?矩陣各維的下標從0開始
如果indices參數是一個標量,那麼返回的是一個向量,維數=矩陣的維數,向量的值其實就是在矩陣中對應的下標。如6*7*8*9的矩陣,1621/(7*8*9)=3,(1621-3*7*8*9)/(8*9)=1,(1621-3*7*8*9-1*8*9)/9=4,(1621-3*7*8*9-1*8*9-4*9)=1。所以返回的向量爲array(3,1,4,1)
如果indices參數是一個向量的,那麼通過該向量中值求出對應的下標。下標的個數就是矩陣的維數,每一維下標組成一個向量,所以返回的向量的個數=矩陣維數。如7*6的矩陣,第22個元素是 3*6+4,所以對應的下標是(3,4),那麼返回的值是 array([3]),array([4])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.