使用索引对数组进行排序会导致数组的索引太多

时间:2017-10-11 11:57:04

标签: python numpy

我试图根据其值对字典键进行排序。所以我使用了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]]

1 个答案:

答案 0 :(得分:1)

在Python 3中, dir(np.array(colour_map.keys()))表明此类不符合array_like https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.array.html

文档中指定的numpy.array要求

array_like

更详细地探讨了np.array的定义

array_like似乎没有检查my_object是否满足,并且很乐意从一个不满足它的对象构造一个Numpy数组。

然后,当您尝试索引它时,索引不起作用。

以下是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!

结果:

Row: User_id | Loginstatus | Timestamp
     5           Attempt        most recent 
     5           Attempt        .
     5           Logoff         .
     5           Login          .
     5           Attempt        .
     5           Attempt        .
     5           Attempt        . 
     5           Attempt        .
     5           Logoff         .
     5           Login          .
     5           Logoff         . 
     5           Login          .