Demystifying Numpy view() Function in Python

We are all familiar with an array and how to access elements in an array. And we also know about slicing operations in python. So we will move to the concept of numpy.view() in this article. In this article, we will learn about how to view array data using a different type and data type? Creating a view on the structured array. How will the changes in view function affect the original array? Convert an array into recarray by using the view function. With that, we also learn what the difference between view and copy function is.

The numpy.view() is another way of viewing the array. It is the view of the new array with original data. This function will create the reference to an existing array. The changes will be reflected in the original array. 

Syntax

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

Parameters

  • dtype: data type descriptor
  • type: type of the returned view

Numpy view(): Viewing array data using a different type and data type

import numpy as np
x=np.array([(5,6,7,8)],dtype=[('a', np.int8), ('b', np.int8),('c',np.int8),('d',np.int8)])
result=x.view(dtype=np.int16, type=np.matrix)
print(type(result),result)

Import a numpy module. Declaring an array and its data type. Using numpy.view to view array in a different type and data type.

Output

<class 'numpy.matrix'> [[1541 2055]]

Numpy view(): None as dtype in the function

import numpy as np
x=np.array([(5,6)],dtype=[('a', None), ('b', None)])
result=x.view(dtype=None)
print(result)

Here we are using None as datatype in a view function. Let us see the output for the program. As it’s an alias of ‘float_,’ the dtype of the new array will be float.

Output

[5. 6.]

Numpy view(): Creating a view on the structured array

import numpy as np
x = np.array([(5,4),(1,2)], dtype=[('a', np.int8), ('b', np.int8)])
result=x.view(dtype=np.int8).reshape(-1,2)
print(result)

Import a numpy module. In this program, we are creating a numpy view function on the structured array. Reshaping the array to (-1,2).

Output

[[5 4]
 [1 2]]

Numpy view: Changes will be reflected in the original array

import numpy as np
x = np.array([(5,4),(1,2)], dtype=[('a', np.int8), ('b', np.int8)])
print("Before using view function:",x)
result=x.view(dtype=np.int8).reshape(-1,2)
result[0,1]=7
print("After using view function:",x)

We have already studied that changes will be reflected in the original array. Let us check it now. Here we are using the slice operation. We are changing the second element in the first term of the list as a result. But the changes are also made in the original array.

Output

Before using view function: [(5, 4) (1, 2)]
After using view function: [(5, 7) (1, 2)]

Numpy view: Convert an array to a recarray

import numpy as np
input=np.array([(4,5)],dtype=[('a',np.int16),('b',np.int16)])
result=input.view(np.recarray)
result.a

Import a module. Here we are converting an array into a recarray by using the numpy view function. Let us see the result.

Output

array([4], dtype=int16)

Numpy view: Incrementing in different data types

1. Incrementing in data type ‘int8’

import numpy as np
x = np.arange(5, dtype ='int8')
print("Input is:", x)
result = x.view('int8')
print("Before Incrementing",x)
result+=1
print("After Incrementing",x)

Import a module. Declaring the array from 0 to 5 by using the numpy arange function. Printing x. Using view function. After incrementing in the view function. Printing the x. But the value of the x is also changed.

Output

Input is: [0 1 2 3 4]
Before Incrementing [0 1 2 3 4]
After Incrementing [1 2 3 4 5]

2. Incrementing in data type ‘int16’

import numpy as np
x = np.arange(10, dtype ='int16')
print("Input is:", x)
result = x.view('int16')
print("Before Incrementing",x)
result+=1
print("After Incrementing",x)

Output

Input is: [0 1 2 3 4 5 6 7 8 9]
Before Incrementing [0 1 2 3 4 5 6 7 8 9]
After Incrementing [ 1  2  3  4  5  6  7  8  9 10]

Numpy view: Trying to change to a dtype of a different size

import numpy as np
x = np.array([(5,4,8),(1,2,9)], dtype=np.int16)
result=x[:,0:2]
result.view(dtype=[('width', np.int16), ('length', np.int16)])

In this program, we are trying to change the data type to a different size. It is not possible.

Output

Traceback (most recent call last):
  File "C:\Users\AppData\Local\Programs\Python\Python39\refresh.py", line 28, in <module>
    result.view(dtype=[('width', np.int16), ('length', np.int16)])
ValueError: To change to a dtype of a different size, the array must be C-contiguous

What is the difference between view and copy function in numpy?

copy()view()
It creates the external copy with a new reference to the array. It creates a reference to an existing array.
In array, one element is modified, then it will not reflect the original array.In array, one element is modified, then it will reflect in the original array.

Frequently Asked Questions

1. Is it possible to change to a data type of different size?

No, it is not possible to change to a data type of a different size.

2.  What happens if we try to change to a data type of different size? 

It will show a Value Error if we try to change to a data type of a different size.

Conclusion

So far, we have completely learned about the view function in python. We have learned a lot of things in this article. These are the beneficial and necessary things to learn as a python programmer.

We hope this article is easy to understand. In case of any queries, do let us know in the comment section.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments