NumPy ndarray.data
The ndarray.data
attribute provides a Python buffer object pointing to the start of the array’s data.
This attribute allows direct access to the underlying memory of the array.
Syntax
ndarray.data
Attributes
Attribute | Type | Description |
---|---|---|
data | buffer object | A buffer object pointing to the start of the array’s data in memory. |
Return Value
Returns a Python buffer object that points to the start of the array’s memory.
Examples
1. Accessing the Data Buffer of an ndarray
In this example, we create a NumPy array and access its data
attribute to obtain the memory buffer.
import numpy as np
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5], dtype=np.int32)
# Access the data buffer of the array
buffer = arr.data
# Print the memory address of the buffer
print("Memory address of data buffer:", buffer)
Output:
Memory address of data buffer: <memory at 0x7f6303904940>
The output shows the memory location of the buffer where the array’s data is stored.
2. Using ndarray.data
to View the Memory Contents
Here, we access the raw memory content of the array using the tobytes()
method.
import numpy as np
# Create a NumPy array
arr = np.array([10, 20, 30, 40], dtype=np.int16)
# Access the data buffer
buffer = arr.data
# Convert the buffer to bytes to inspect raw memory content
raw_data = arr.tobytes()
# Print the memory buffer and raw data
print("Memory buffer address:", buffer)
print("Raw memory data:", raw_data)
Output:
Memory buffer address: <memory at 0x7f8b16400940>
Raw memory data: b'\n\x00\x14\x00\x1e\x00(\x00'
The raw data is displayed as bytes, representing the integer values stored in memory.
3. Checking If Two Arrays Share the Same Memory Buffer
In this example, we check whether two different arrays share the same data buffer.
import numpy as np
# Create an initial NumPy array
arr1 = np.array([5, 10, 15, 20], dtype=np.int32)
# Create a view of the array
arr2 = arr1.view()
# Check if both arrays share the same memory buffer
same_buffer = arr1.data == arr2.data
# Print memory addresses and buffer comparison
print("Memory buffer address of arr1:", arr1.data)
print("Memory buffer address of arr2:", arr2.data)
print("Do arr1 and arr2 share the same memory buffer?", same_buffer)
Output:
Memory buffer address of arr1: <memory at 0x7f372fc00a00>
Memory buffer address of arr2: <memory at 0x7f372fc00a00>
Do arr1 and arr2 share the same memory buffer? True
Since arr2
is a view of arr1
, both arrays share the same memory buffer.