Insworn
Insworn

Reputation: 71

With Numpy how to turn a given 3D array into an array of 3x3 matrices

I'm learning Numpy at the Moment and I'm trying to wrap my head around Reshaping. I have a 3D-Array that looks like this (values are random but the shape is important):

[[[37. 56. 56. 54. 82. 85. 68. 46.  6.]]

[[96. 20. 53. 52. 79. 94. 59. 29. 40.]]

[[57. 59. 38. 53. 88. 96. 61. 62. 48.]]

[[32. 92. 56. 52. 74. 12. 63. 58. 81.]]

[[16. 89. 24. 26. 33. 82. 80. 66. 89.]]]

and I want to turn it into an array of 3x3 Matrices like that:

[[[37. 56. 56.]
  [54. 82. 85.]
  [68. 46.  6.]]

 [[96. 20. 53.]
  [52. 79. 94.]
  [59. 29. 40.]]

 [[57. 59. 38.]
  [53. 88. 96.]
  [61. 62. 48.]]

 [[32. 92. 56.]
  [52. 74. 12.]
  [63. 58. 81.]]

 [[16. 89. 24.]
  [26. 33. 82.]
  [80. 66. 89.]]]

If I understood everything correctly up until now this should be possible with numpy.reshape but I'm not getting it to work. Can somebody point me in the right direction?

Upvotes: 0

Views: 1666

Answers (1)

Lock-not-gimbal
Lock-not-gimbal

Reputation: 309

You need to relize what shape the array is. Looking at the one you currently have, it's (5, 1, 9): 5 elements in the top-level dimension, each element is an array of shape (1, 9).

Now you want to have the same number of top-level elements (think rows), but inside arrays of shape (3, 3), so you need to call:

your_array.reshape((5, 3, 3))

In the numpy docs you can find examples of usage and important info on the behavior, e.g. when it would return a view and when a copy.

Upvotes: 2

Related Questions