NumPy Tutorial NumPy Statistics NumPy References

NumPy - ndarray.view() function



The NumPy ndarray.view() returns a view of the array. The created view has different id but any changes made to the view will affect the original array. The syntax for using this function is given below:

Syntax

numpy.ndarray.view([dtype][, type])

Parameters

dtype Optional. Specify data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as the original array.
type Optional. Specify type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation.

Return Value

Returns a view of the array.

Example:

In the example below, ndarray.view() is used to create a view (shallow copy) of a given array.

import numpy as np

x = np.array([[1,2,3],
              [4,5,6]])

#creating a view of array x
y = x.view()

#displaying array x
print("id of x =", id(x))
print("x =")
print(x)

#displaying array y
print("\nid of y =", id(y))
print("y =")
print(y)

#changing content of y
#this will change x and y both
y[0,0] = 100

#after operation, array x
print("\nx =")
print(x)

#after operation, array y
print("\ny =")
print(y)

The output of the above code will be:

id of x = 140004172440752
x =
[[1 2 3]
 [4 5 6]]

id of y = 140004172443536
y =
[[1 2 3]
 [4 5 6]]

x =
[[100   2   3]
 [  4   5   6]]

y =
[[100   2   3]
 [  4   5   6]]

❮ NumPy - Functions