我正在尝试根据字典键的值对它进行排序。因此,我使用 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]]
最佳答案
在 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!
关于python - 使用索引对数组进行排序会导致数组索引过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46687617/