0

I have an input numpy array as follows:

import numpy as np

my_array = [
        np.array([[[1,  10]],
                 [[2,  11]]], dtype=np.int32),
        np.array([[[3, 12]],
                  [[4, 13]],
                  [[5, 14]]], dtype=np.int32),
        np.array([[[6,  15]],
                  [[7,  16]],
                  [[8,  17]]], dtype=np.int32)
]

I want to get two arrays (1 for each column) so that:

array1 = [1, 2, 3, 4, 5, 6, 7 ,8]
array2 = [10, 11, 12, 13, 14, 15, 16, 17]

I tried with a list comprehension but it didn't work:

[col[:] for col in my_array]

2 Answers 2

3

You can loop through the arrays and append to the new ones:

array1 = []
array2 = []

for array in my_array:
  for nested_array in array:
    # nested_array is of form [[ 1 10]] here, you need to index it
    # first with [0] then with the element you want to access [0] or [1]
    array1.append(nested_array[0][0])
    array2.append(nested_array[0][1])

You just have to think about the structure of the input data and how to get the values you need in the order that you need.

The output:

>>> array1
[1, 2, 3, 4, 5, 6, 7, 8]
>>> array2
[10, 11, 12, 13, 14, 15, 16, 17]
Sign up to request clarification or add additional context in comments.

Comments

1

You can try this:

>>> from numpy import array
>>> import numpy as np
>>> my_array = [array([[[1,  10]],
        [[2,  11]]], dtype='int32'), array([[[3, 12]],

        [[4, 13]],
        [[5, 14]]], dtype='int32'), array([[[6,  15]],

        [[7,  16]],
        [[8,  17]]], dtype='int32')]
# One way
>>> np.concatenate(my_array,axis=0)[...,0]    # [...,1] would give the other one
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8]], dtype=int32)
# Other way:
>>> np.concatenate(my_array,axis=0)[...,0].reshape(-1,) # [...,1].reshape(-1,0) would be the other one
array([1, 2, 3, 4, 5, 6, 7, 8], dtype=int32)

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.