I have a
(96, 32, 8)
mv.strides == (1,)
In : import numpy as np
In : x = np.ones((2, 3, 4))
In : x.data
Out: <memory at 0x7f371aa849a8>
In : x.data.strides
Out: (96, 32, 8)
Just for clarification, you probably know this but I think it's better to make sure:
(8, )are both one dimensional and
(20, 1)are both two-dimensional.
So you don't only want your memoryview flattened but it should be flattened and have an itemsize of 1.
In Python 3.3 the
memoryview.cast method was added that makes flattening your array trivial:
Cast a memoryview to a new format or shape. shape defaults to [byte_length//new_itemsize], which means that the result view will be one-dimensional. The return value is a new memoryview, but the buffer itself is not copied. Supported casts are 1D -> C-contiguous and C-contiguous -> 1D.
The destination format is restricted to a single element native format in struct syntax. One of the formats must be a byte format (‘B’, ‘b’ or ‘c’). The byte length of the result must be the same as the original length.
So it only works if you cast to char (
c), unsigned char (
B) or signed chars (
b) and it's C-contiguous.
>>> import numpy as np >>> memview = memoryview(np.ones((2, 3, 4))) >>> memview.cast('b').strides # or 'B' or 'c' (1, )
However this is flattened and interpreted as 1-byte values. If you just want it flattened you need to cast it to the original type again:
That will be one-dimensional but it won't have strides of
(1, ) because floats are 8 bytes (at least if it's
>>> memview.cast('b').cast(memview.format).strides (8, )