从数组索引中创建新数组

问题描述 投票:0回答:1

假设我有以下数组。

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

我想组成四个新的数组 其中第一个新数组是由所有嵌套数组的第一列建立的 my_array,第二列从第二列开始,等等。

A = array([5,-6,9,-1,-7,-1,4,-9,-4,-7,7,-4,6,1,-4,0,4,3,6,0])

而第二个数组形成的第二列各自嵌套,像这样。

B = array([7,0,-7,6,-8,5,-3,0,6,-3,9,7,0,6,-1,8,5,7,-1,5])

我怎么能这样做呢?

python arrays multidimensional-array numpy-ndarray
1个回答
1
投票
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]

其结果是:

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])
© www.soinside.com 2019 - 2024. All rights reserved.