Reputation: 3983
Suppose I have the following array:
print(my_array)
(array([[[[5, 7, 3, 1],
[-6, 0, -8, -2],
[ 9 -7, -5, -9],
[-1, 6, 0, 1],
[-7, -8 , -3, 4]]],
[[[-1, 5, -2, 2],
[4, -3, -1, 2],
[-9, 0, 7, 1],
[-4, 6, -5, -8],
[-7, -3, 0 , 1]]]]),
array([[[[ 7, 9 , 4, -3 ],
[-4, 7, -1, -9],
[6, 0, -3, -7],
[ 1, 6, 9, -3],
[-4, -1, -9 , -6]]],
[[[ 0, 8, 2, 6],
[4, 5, 1, 2],
[3, 7, 5, 2],
[6, -1, 9, 5],
[ 0, 5, 7, 7]]]]))
Then I want to form four new arrays, where the first new array is created from first columns of all nested arrays in my_array
, the second from second columns etc.. such that
A = array([5,-6,9,-1,-7,-1,4,-9,-4,-7,7,-4,6,1,-4,0,4,3,6,0])
And the second array formed by second columns of each nested, like so:
B = array([7,0,-7,6,-8,5,-3,0,6,-3,9,7,0,6,-1,8,5,7,-1,5])
How can I do this?
Upvotes: 0
Views: 38
Reputation: 800
import numpy as np
# Create example arrays
arr1 = np.random.randint(10,size=(5, 4))
arr2 = np.random.randint(10,size=(5, 4))
arr3 = np.random.randint(10,size=(5, 4))
arr4 = np.random.randint(10,size=(5, 4))
# Combine all the arrays to match the dimensions mentioned in the question
arr_comb = np.array([[arr1, arr2],[arr3, arr4]])
print("Old array:")
print(arr_comb)
new_column_length = np.shape(arr_comb)[0] * np.shape(arr_comb)[1] * np.shape(arr_comb)[2]
# Reshape the array into a new array. The columns of the new array are what you requested
new_comb_arr = arr_comb.reshape(new_column_length,-1)
# e.g
print("First column of new array")
new_comb_arr[:,0]
Which results in:
Old array:
[[[[2 7 0 0]
[0 1 7 3]
[5 7 4 2]
[4 5 3 6]
[4 8 2 0]]
[[4 6 3 4]
[6 5 3 7]
[6 2 7 4]
[9 1 8 2]
[3 9 2 2]]]
[[[6 8 3 4]
[0 6 6 6]
[1 8 1 2]
[4 2 6 4]
[7 8 0 2]]
[[2 6 4 1]
[4 7 1 4]
[8 0 5 6]
[4 7 4 7]
[8 9 4 5]]]]
First column of new array
array([2, 0, 5, 4, 4, 4, 6, 6, 9, 3, 6, 0, 1, 4, 7, 2, 4, 8, 4, 8])
Upvotes: 1