If I have a numpy array with each element being another numpy array of varying lengths (not an ndarray because of this), how can I sort the outer array by descending lengths of the inner array?
如果我有一个numpy数组,每个元素是另一个不同长度的numpy数组(因为这不是一个ndarray),我如何通过内部数组的下降长度对外部数组进行排序?
For example:
a = np.array([np.array([1]), np.array([1, 2, 3]), np.array([1, 2])])
would be sorted as:
将被排序为:
[[1, 2, 3], [1, 2], [1]]
2 个解决方案
#1
2
An alternative could be to just sort by length the old Python way for lists and then reconstruct an array.
另一种方法是按照旧的Python方式对列表进行排序,然后重构数组。
np.array(sorted(b, key=len, reverse=True))
Remaining in NumPy-land probably isn't providing you any benefits here anyways.
保留在NumPy-land可能无论如何都不会为您提供任何好处。
#2
1
For array of arrays as output -
对于数组数组作为输出 -
a[np.argsort([len(i) for i in a])[::-1]]
Sample run -
样品运行 -
In [329]: a
Out[329]: array([array([1]), array([1, 2, 3]), array([1, 2])], dtype=object)
In [330]: a[np.argsort([len(i) for i in a])[::-1]]
Out[330]: array([array([1, 2, 3]), array([1, 2]), array([1])], dtype=object)
# If you need a list of lists as output
In [341]: [i.tolist() for i in _]
Out[341]: [[1, 2, 3], [1, 2], [1]]
#1
2
An alternative could be to just sort by length the old Python way for lists and then reconstruct an array.
另一种方法是按照旧的Python方式对列表进行排序,然后重构数组。
np.array(sorted(b, key=len, reverse=True))
Remaining in NumPy-land probably isn't providing you any benefits here anyways.
保留在NumPy-land可能无论如何都不会为您提供任何好处。
#2
1
For array of arrays as output -
对于数组数组作为输出 -
a[np.argsort([len(i) for i in a])[::-1]]
Sample run -
样品运行 -
In [329]: a
Out[329]: array([array([1]), array([1, 2, 3]), array([1, 2])], dtype=object)
In [330]: a[np.argsort([len(i) for i in a])[::-1]]
Out[330]: array([array([1, 2, 3]), array([1, 2]), array([1])], dtype=object)
# If you need a list of lists as output
In [341]: [i.tolist() for i in _]
Out[341]: [[1, 2, 3], [1, 2], [1]]