我试图根据其值对字典键进行排序。因此,我使用了numpy的argsort对值进行升序排序。但是,当我尝试根据值索引对键进行排序时,出现错误:


  IndexError:数组索引过多


我在这里做错了什么?

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]]

最佳答案

在Python 3中,
dir(np.array(colour_map.keys()))表明该类不满足array_like的要求,该要求在numpy.array https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.array.html的文档中被指定为必需

array_like的定义在此处numpy: formal definition of "array_like" objects?进行了更详细的探讨。

似乎np.array不会检查array_like是否满足,并且会很高兴从不满足要求的对象构造一个Numpy数组。

然后,当您尝试对其建立索引时,该索引将不起作用。

这是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!

10-08 05:42
查看更多