【问题标题】:Creating new array from array indexing从数组索引创建新数组
【发布时间】:2020-06-02 23:56:08
【问题描述】:

假设我有以下数组:

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

我该怎么做?

【问题讨论】:

  • 你介意使用 numpy 数组吗?如果是这样,解决方案非常简单。
  • 是的,我想要那个。

标签: python arrays multidimensional-array numpy-ndarray


【解决方案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])

【讨论】:

  • 有没有办法重塑新数组而不像arr_comb.reshape(16,-1)那样明确说明总行数?
  • 你的数组会一直是方形的吗?
  • 不是方形的,是(5,4)数组。
  • 哦,你是对的。我的错 :)。你的数组的大小总是一样的吗?
  • 无论如何,我已经概括了我的答案。现在它支持你所要求的。但数组必须具有相同的大小(不一定是正方形)。
猜你喜欢
  • 2020-11-23
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-27
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
相关资源
最近更新 更多