繁体   English   中英

Python中多维数组中的Argsort问题

[英]Argsort issue in multi-dimensional array in Python

我有数组I1 (shape=(1, 10, 2))I2 (shape=(2,)) 我正在尝试使用argsort()进行排序,但出现I2错误。

import numpy as np

I1=np.array([[[0, 1],
        [0, 3],
        [1, 2],
        [1, 4],
        [2, 5],
        [3, 4],
        [3, 6],
        [4, 7],
        [5, 4],
        [6, 7]]])

             
I2=np.array([[[0, 1],
        [0, 3],
        [1, 2],
        [1, 4],
        [2, 5],
        [3, 4],
        [3, 6],
        [4, 7],
        [5, 4],
        [6, 7]],
                [[0, 1],
                 [0, 3],
                 [1, 2],
                 [1, 4],
                 [2, 5],
                 [3, 4],
                 [3, 6],
                 [4, 7]]])             

order1 = I1[0,:, 1].argsort()
print("order1 =",[order1])
order2 = I2[0,:, 1].argsort()
print("order2 =",[order2])

错误是

in <module>
    order2 = I2[0,:, 1].argsort()

IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed

如果您要打印I2 ,您将很快看到导致问题的原因:

array([list([[0, 1], [0, 3], [1, 2], [1, 4], [2, 5], [3, 4], [3, 6], [4, 7], [5, 4], [6, 7]]),
       list([[0, 1], [0, 3], [1, 2], [1, 4], [2, 5], [3, 4], [3, 6], [4, 7]])],
      dtype=object)

I2不是一个三维数组,而是一个一维列表数组(每个单独的列表由一个 2 元素列表组成)。

实际上,当您使用最近的 NumPy 创建I2时,您还应该看到DeprecationWarning

VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  I2=np.array([[[0, 1],

这基本上确定了相同的问题。 实际上,它指出“来自不规则的嵌套序列”。 Ragged 是这里的关键:您的输入外部列表包含两个长度不同的列表。 结果,三维嵌套列表不是“矩形”(盒形)尺寸,而是列表的集合。

如果您计划以这种方式与 NumPy 一起使用您的数据,那么您真的不能:NumPy 用于(快速)对常规数组进行操作,而不是用于不规则数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM