【问题标题】:How to find the index of the min/max object in a numpy array of objects?如何在 numpy 对象数组中找到最小/最大对象的索引?
【发布时间】:2019-09-30 02:48:37
【问题描述】:

在一个 numpy 对象数组中(其中每个对象都有一个数字属性 y,可以通过 get_y() 方法检索),我如何获取具有最大(或最小)y 属性的对象的索引(没有显式循环;为了节省时间)?如果 myarray 是一个 python 列表,我可以使用以下内容,但 ndarray 似乎不支持索引。此外,numpy argmin 似乎不允许提供密钥。 minindex = myarray.index(min(myarray, key = lambda x: x.get_y()))

【问题讨论】:

  • 为什么是数组而不是列表?您已经知道如何使用列表。列表的迭代速度更快。
  • 快速 numpy 计算需要数字 dtypes,而不是对象。
  • 谢谢,但是如果 numpy.argmin() 之类的东西(假设)可用于这种情况,难道不会比列表迭代更快吗?我有点困惑。请帮忙。
  • 这不是 numpy 的工作方式;操作不仅神奇地更快,因为它们在另一个对象内。 numpy 更快的原因是因为数组可以具有固定的表示,因此它们可以顺序存储在内存中,因此可以一次全部加载到缓存中,这与列表不同,其中每个对象只是指向在内存中浮动的其他对象的指针那必须查一下。 numpy中的object dtype等价于this,和python列表一样。所以在这里使用 numpy 没有任何好处。
  • @alkasm:非常感谢,但我认为当数组的对象是同质的(相同的类型和大小)时,对象 dtype 在内存中的处理方式类似,因为每个对象的大小都是已知的从显式用户指定的 dtype 或隐式作为对象中组件大小的总和,从而允许固定大小的连续分配。我需要更仔细地学习。您能否为我推荐一些阅读材料(来源)。再次感谢。

标签: arrays python-3.x numpy numpy-ndarray


【解决方案1】:

一些计时,比较数字 dtype、对象 dtype 和列表。得出你自己的结论:

In [117]: x = np.arange(1000)                                                   
In [118]: xo=x.astype(object)                                                   

In [119]: np.sum(x)                                                             
Out[119]: 499500
In [120]: np.sum(xo)                                                            
Out[120]: 499500

In [121]: timeit np.sum(x)                                                      
10.8 µs ± 242 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [122]: timeit np.sum(xo)                                                     
39.2 µs ± 673 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [123]: sum(x)                                                                
Out[123]: 499500
In [124]: timeit sum(x)                                                         
214 µs ± 6.58 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [125]: timeit sum(xo)                                                        
25.3 µs ± 4.54 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [126]: timeit sum(x.tolist())                                                
29.1 µs ± 26.7 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [127]: timeit sum(xo.tolist())                                               
14.4 µs ± 120 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [129]: %%timeit  temp=x.tolist() 
     ...: sum(temp)                                                                      
6.27 µs ± 18.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2018-04-08
    • 2014-06-02
    • 2015-03-15
    相关资源
    最近更新 更多