numpy.ndarray.tobytes — NumPy v2.6.dev0 Manual

Learn | NEPs | User Guide | API reference | Building from source | Development | Release notes | NumPy’s module structure | Array objects | The N-dimensional array (ndarray) | Scalars | Data type objects (dtype) | Data type promotion in NumPy | Iterating over arrays | Standard array subclasses | Masked arrays | The array interface protocol | Datetimes and timedeltas | Universal functions (ufunc) | Routines and objects by topic | Typing (numpy.typing) | NumPy C-API | Array API standard compatibility | CPU/SIMD optimizations | Thread Safety | Global Configuration Options | NumPy security | Testing guidelines

method

ndarray.tobytes(order='C')

#

Construct Python bytes containing the raw data bytes in the array.

Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object is produced in C-order by default. This behavior is controlled by the order parameter.

Parameters:order{‘C’, ‘F’, ‘A’}, optionalControls the memory layout of the bytes object. ‘C’ means C-order, ‘F’ means F-order, ‘A’ (short for Any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. Default is ‘C’.

Returns:sbytesPython bytes exhibiting a copy of a’s raw data.

See also

frombuffer

Inverse of this operation, construct a 1-dimensional array from Python bytes.

Examples

>>> importnumpyasnp>>> x=np.array([[0,1],[2,3]],dtype='<u2')>>> x.tobytes()b'\x00\x00\x01\x00\x02\x00\x03\x00'>>> x.tobytes('C')==x.tobytes()True>>> x.tobytes('F')b'\x00\x00\x02\x00\x01\x00\x03\x00'

1 1