Home>

### python - i want to speed up the calculation of for statements with numpy

I want to convert a one-dimensional array x to a three-dimensional array y as shown below.
x is an array containing 0-9215.
I want to extract this array x by 8 and store it in the depth direction of the array y of 256 × 6 × 6.
For example, store x [0: 8] in y [0: 8,0,0], store x [9:16] in y [0: 8,0,1], and store y [0: 8,6]. Up to, 6]
After storing, I want to store from y [8: 16,0,0] to y [8: 16,6,6].
I created a program with a for statement, but it took a long time to repeat the calculation.
I asked if you can speed up with numpy's reshape etc.

The program in the for statement is as follows.

``````import numpy as np
x = np.arange (1152 * 16)
print (x)
y = np.zeros ((256,6,6))
for k in range (32):
for i in range (6):
for j in range (6):
y [8 * k: 8 * (k + 1), i, j] = x [k * 8 * 36 + (i + j) * 8: k * 8 * 36 + (i + j + 1) * 8 ]
print (y)``````
• Answer # 1

You can reshape it to 4 dimensions, rearrange the dimensions with transpose, and then reshape it to the desired shape.

``y = x [: 256 * 6 * 6] .reshape ((32, 6, 6, 8)). transpose ((0, 3, 1, 2)). Reshape ((256, 6, 6))``

Imagine how the original array was split and rearranged.