numpy.ndarray.view() in Python

In this tutorial, we will learn about numpy.ndarray.view() in python with some practical examples.

  • In Python, lists can be used similarly to arrays, but their processing speed is relatively slow.
  • NumPy aims to offer an array object that is up to 50 times faster than traditional python lists.
  • Unlike lists, NumPy arrays are stored in a contiguous block of memory, allowing for highly efficient access and manipulation.

numpy.ndarray.view() function in python

In numPy, the array object is referred to as an ndarray.

  • To know more about the “ndarray”, we need to create a NumPy ndaaray object using the array() function.
  • ndarrays is known as n-dimensional arrays.
  • The very first step while creating an ndarray is to use the statement “import numpy”.
  • we can use list, tuple or any array-like object in ndarray.

creating an ndarray using array() function

import numpy as np
arr1 = np.array((8, 9, 10, 11, 12))
print(arr1)

output:

[8,  9,  10,  11,  12]

The NumPy array object includes a property named dtype, which returns the array’s data type.

import numpy as np
array = np.array([8, 9, 10, 11])
print(array.dtype)

output:

int64

So, In above code the array.dtype is an attribute that specify what data type the array belongs to and in the above case the array belongs to int with 64 bit integers.

ndarray.view() in python with example

NumPy’s ndarray.view() method creates a new array object that shares the same data as the original array.

  • Any changes made to the data in either the original array or the view will be reflected in the other.
import numpy as np
# Create a NumPy array1 with elements [8, 9, 10, 11, 12]
array1 = np.array([8, 9, 10, 11, 12])
# Create a view of the array `array1` and assign it to `x`
x = array1.view()
# Modify the first element of `array1` to 20
array1[0] = 20
# Print the modified `array1`
print(array1)
# Print `x` to see the view of the modified `array1`
print(x)

output:

[20  9 10 11 12]
[20  9 10 11 12]

The code demonstrates that when you create a view of a NumPy array, changes to the original array are reflected in the view. Therefore, after modifying array1[0] to 20, both array1 and x will show the updated values.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top