Numpy.ndarray.data, slices and tobytes

I have some confusion somewhere about these three.

I have a numpy.ndarray A, for which I do a slice A.data[0:1] of the memoryview A.data.

Question: Does this slice is a memoryview to one byte of A.data ? How could I get one? It doesn’t seem to be, since doing A.data[0:1].tobytes() I get the same as when doing A.data.tobytes(). Note: The shape of A is (1, 99, 9). The slice seems to be relative to the dimensions in the shape.

Example

import numpy as np
A = np.array([[1,2,3,4]])
m1 = A.data
m2 = A.data[0:1]
m1 == m2  # True
b1 = A.data.tobytes()
b2 = A.data[0:1].tobytes()
b1 == b2  # True

I would like to get a memoryview of the of the first b'\x01, and other pieces, in b'\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00'.

I can do b = A.data.tobytes() or b = A.tobytes() and then the slices b[0:1] is what I want. However, if I understood correctly the implementation of tobytes() a copy of the data in A.data is made to create b.

It looks like the arr.data memoryview only lets you slice over the first axis. If you switch to bytes(A[0].data[:1]), you get b'\x01\x00\x00\x00\x00\x00\x00\x00'.

You can get a flat array of bytes (uint8) with A.view('B').reshape(-1).

>>> import numpy as np
>>> A = np.array([[1,2,3,4]])
>>> bytes(A.view('B').reshape(-1).data[:1])
b'\x01'

I see. I would have expected the memoryview to not know anything about shapes.

Do you know if that reshape copies the data? It returns a new array, so I guess it must, isn’t it?
In that case I could slice A.tobytes(). The actual array is large. I would like to not have to make a copy.

I just found that there is a memoryview.cast that can modify the shape. So, I could do

import math
A.data.cast('B', shape=(math.prod(A.shape)*4,))[0:1] 

Let me check if that cast only affects the memoryview’s information about shape and data type and does not have to make a copy.

It will only make a copy if one can’t be avoided due to the new shape. See the docs.