Home>

### python - what is the difference between these two numpy 2d array implementations?

What are the differences in how numpy's two-dimensional array is implemented?
``````a1 = np.arange (9) .reshape (3, -3)
a1 = np.arange (9) .reshape (3, 3)``````

I would like to tell you the difference between the two. Is it necessary to write these separately?

• Answer # 1

The former is an unacceptable calling method in the specification and should be written as reshape (3, -1).

newshape: int or tuple of ints

The new shape should be compatible with the original shape.If an integer, then the result will be a 1-D array of that length.
One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

Source:: numpy.reshape — NumPy v1.17 ManualBoldis the quote

After answering the question, read it a little.

Main topic

A question about the difference between the two.

``````a1 = np.arange (9) .reshape (3, -1)
a2 = np.arange (9) .reshape (3, 3)``````

Speaking only the results,neither will change.
The former goes through an extra process to determine an undetermined value, but there is almost no difference in the measurement.

``````import timeit
import numpy as np
def reshape1 (arr):
arr.reshape (3, -1)
def reshape2 (arr):
arr.reshape (3, 3)
src_arr = np.arange (9)
print (
'(3, -1):', timeit.timeit (lambda: reshape1 (src_arr), number = 1_000_000)
)
print (
'(3, 3):', timeit.timeit (lambda: reshape2 (src_arr), number = 1_000_000)
)``````

Execution resultpaiza.io

``````(3, -1): 0.3540483240503818
(3, 3): 0.34941665700171143``````

Wouldn't it be better to use one that you think is easy to understand?

Why does reshape (3, -3) work?

Because the implementation uses dimensions [i]<0 instead of dimensions [i] == -1

``````for (i = 0;i= 0) {
if (s_known == 0 || s_original% s_known! = 0) {
raise_reshape_size_mismatch (newshape, arr);
return -1;
}
dimensions [i_unknown] = s_original/s_known;
}``````

numpy/shape.c at v1.17.4 · numpy/numpy · GitHub