1

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?

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]]
1
  • Why not just use list objects in this case? At least, as the outer object? Commented Nov 13, 2017 at 18:41

2 Answers 2

3

An alternative could be to just sort by length the old Python way for lists and then reconstruct an array.

np.array(sorted(b, key=len, reverse=True))

Remaining in NumPy-land probably isn't providing you any benefits here anyways.

Sign up to request clarification or add additional context in comments.

Comments

2

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.