NumPy ndarray.dumps()

The numpy.ndarray.dumps() method serializes a NumPy array into a byte string using the Python pickle module. This allows for storing or transmitting array data efficiently.

Syntax

</>
Copy
ndarray.dumps(protocol=None)

Parameters

ParameterTypeDescription
protocolint, optionalSpecifies the pickling protocol version. If None, the highest available protocol is used.

Return Value

Returns a bytes object containing the serialized data of the array.


Examples

1. Serializing a NumPy Array Using ndarray.dumps()

This example demonstrates how to serialize a NumPy array into a byte string using dumps().

</>
Copy
import numpy as np

# Creating a NumPy array
arr = np.array([[1, 2, 3], [4, 5, 6]])

# Serializing the array to a byte string
serialized_data = arr.dumps()

# Printing the serialized byte string
print(serialized_data)

Output:

b'\x80\x02cnumpy._core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02c_codecs\nencode\nq\x03X\x01\x00\x00\x00bq\x04X\x06\x00\x00\x00latin1q\x05\x86q\x06Rq\x07\x87q\x08Rq\t(K\x01K\x02K\x03\x86q\ncnumpy\ndtype\nq\x0bX\x02\x00\x00\x00i8q\x0c\x89\x88\x87q\rRq\x0e(K\x03X\x01\x00\x00\x00<q\x0fNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x10b\x89h\x03X0\x00\x00\x00\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\x05\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00q\x11h\x05\x86q\x12Rq\x13tq\x14b.'

The output is a byte string representing the serialized NumPy array, which can be stored or transmitted.

2. Deserializing an Array Using pickle.loads()

Here, we serialize an array using dumps() and then restore it using pickle.loads().

</>
Copy
import numpy as np
import pickle  # Required to deserialize the data

# Creating a NumPy array
arr = np.array([[10, 20], [30, 40]])

# Serializing the array
serialized_data = arr.dumps()

# Deserializing back to NumPy array
restored_arr = pickle.loads(serialized_data)

# Printing the deserialized array
print(restored_arr)

Output:

[[10 20]
 [30 40]]

The array is successfully restored from the serialized byte string, maintaining its original structure and data.

3. Using a Specific Pickling Protocol

In this example, we specify a particular pickling protocol version for serialization.

</>
Copy
import numpy as np
import pickle

# Creating a NumPy array
arr = np.array([1, 2, 3, 4, 5])

# Serializing using protocol version 4
serialized_data = arr.dumps(protocol=4)

# Deserializing back to an array
restored_arr = pickle.loads(serialized_data)

# Printing the deserialized array
print(restored_arr)

Output:

[1 2 3 4 5]

Using a specified pickling protocol can be useful for compatibility with different Python versions.