2017-10-11 92 views
1

我正在嘗試根據其值對字典鍵進行排序。所以我用numpy的argsort來按升序對值進行排序。但是,當我嘗試根據值索引對鍵進行排序時,我得到以下錯誤:使用索引對數組進行排序會導致索引太多

IndexError: too many indices for array

我在做什麼錯在這裏?

import numpy as np 

## Map occurences of colours in image 
colour_map = {} 
#... 
colour_map['#fff'] = 15 
colour_map['#ccc'] = 99 
#... 

## Sort colour map from most frequent to least 
colours   = np.array(colour_map.keys()) # dict_keys(['#fff', '#ccc']) 
col_frequencies = np.array(colour_map.values()) # dict_values([15, 99]) 

indicies = col_frequencies.argsort() 

# Error on below line "IndexError: too many indices for array" 
colours = colours[indicies[::-1]] 
+2

當你調用'.keys()'和'values()'numpy doe不會將它們轉換爲char或整數數組,而是對象數組。 'colours = np.array(list(colour_map.keys()))''後跟'col_frequencies = np.array(list(colour_map.values()))'應該解決這個問題。 – ayhan

+0

@ayhan謝謝修復它。如果你做出答案,我可以接受它。 –

+0

你的代碼可以在'Python 2.7.12'上使用'Numpy 1.13.0'。 – carthurs

回答

1

在Python 3, dir(np.array(colour_map.keys()))表明,這種類不能滿足其被指定爲文檔中是必需的numpy.arrayhttps://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.array.html

array_like的定義在這裏numpy: formal definition of "array_like" objects?

更詳細地進行了探討的 array_like要求

看來np.array不檢查是否滿足array_like,並且會很樂意從一個物體構造一個Numpy數組ct不滿足它。

然後當您嘗試索引它時,索引不起作用。

下面是my_object的一個示例,其設計不是array_like

class my_object(): 
    def greet(self): 
     print("hi!") 

a = my_object() 
a.greet() 
print(dir(a)) # no __array__ attribute 

b = np.array(a) 

b[0] 

結果

hi! 
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'greet'] 
Traceback (most recent call last): 
    File "C:/path/to/my/script.py", 
line 35, in <module> 
    b[0] 
IndexError: too many indices for array 

現在,讓我們嘗試使陣列狀(或至少足夠陣列狀的這個工作):

class my_object(): 
    def greet(self): 
     print("hi!") 

    def __array__(self): 
     return np.array([self]) 

a = my_object() 

b = np.array(a) 

b[0].greet() # Now we can index b successfully 

結果:

hi!