1

Currently, the array I got is

arr = array([array([ 2,  7,  8, 12, 14]), array([ 3,  4,  5,  6,  9, 10]),
   array([0, 1]), array([11, 13])], dtype=object)

How can I convert it into array([[ 2, 7, 8, 12, 14], [ 3, 4, 5, 6, 9, 10], [0, 1], [11, 13]])?

I tried arr.astype(np.int), but failed

2
  • 2
    You have mixed dimensions, which won't work with numpy. EDIT: well, it will work, but you won't be able to use vectorization. You'd probably be better with lists in that case. Commented Sep 2, 2018 at 11:42
  • 1
    Related: How do I stack vectors of different lengths in NumPy? Commented Sep 2, 2018 at 12:02

1 Answer 1

2

The dtype for an array of arrays will always be object. This is unavoidable because with NumPy only non-jagged n-dimensional arrays can be held in a contiguous memory block.

Notice your constituent arrays are already of int dtype:

arr[0].dtype  # dtype('int32')

Notice also your logic will work for a non-jagged array of arrays:

arr = np.array([np.array([ 2,  7,  8]),
                np.array([ 3,  4,  5])], dtype=object)

arr = arr.astype(int)

arr.dtype  # dtype('int32')

In fact, in this case, the array of arrays is collapsed into a single array:

print(arr)

array([[2, 7, 8],
       [3, 4, 5]])

For computations with a jagged array of arrays you may see some performance advantages relative to a list of lists, but the benefit may be limited. See also How do I stack vectors of different lengths in NumPy?

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

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.