0

I was reading this question about numpy, array and reshape. I understand what the OP is doing and his line of code, except the last argument of reshape: 3

According to the documentation of numpy.reshape, the third argument of the function is the order and should be a string {'C', 'F', 'A'}, optional.

So what does the OP argument 3 means?

Side note: In the question, OP places 3 as second argument because it is the function numpy.array.reshape, while in the documentation of numpy.reshape the order is the third argument. But it is because in numpy.reshape the array itself is the first argument.

The numpy.array.reshape documentation page redirects to numpy.reshape page.

sshashank124
  • 31,495
  • 9
  • 67
  • 76
totalMongot
  • 194
  • 8

2 Answers2

2

You are looking at the wrong version of reshape. The relevant one is ndarray.reshape which

allows the elements of the shape parameter to be passed in as separate arguments

Therefore,

a = np.array(...)
a.reshape(3, 4, 5)

is like doing

np.reshape(a, (3, 4, 5))

In the original question, the 3 is simply a part of the reshape operation since the OP is trying to work with an RGB image as a 3D array of shape (height, width, 3)

sshashank124
  • 31,495
  • 9
  • 67
  • 76
0

Consider this code, which runs as expected:

arr = np.arange(12) # arr has 12 element
arr = np.reshape(arr, (3, 4)) 

print(arr) # prints '[[ 0  1  2  3] [ 4  5  6  7] [ 8  9 10 11]]'

Now, consider this code which has an error in it:

arr = np.arange(24) # arr has 24 element

# next line will fail, because (3, 4) can only have 12 element... but 'arr' has 24 element
arr = np.reshape(arr, (3, 4)) 

print(arr)

What can we do to solve it?

A solution would be, to have 3 parents list inside the main list, where each parent list has a structure of (4, 2). So together these 3 parents list can hold 8 * 3 or 24 items. That's why the next block of code runs without any error.

arr = np.arange(24) # arr has 24 element

arr = np.reshape(arr, (3, 4, 2))  # 3 means it will have 3 parent list that has a structure of (4, 2)

print(arr) # prints '[  [[ 0  1] [ 2  3] [ 4  5] [ 6  7]]    [[ 8  9] [10 11] [12 13] [14 15]]    [[16 17] [18 19] [20 21] [22 23]]  ]'
Prottay
  • 385
  • 5
  • 9