Asarray

The asarray()function is used when you want to convert an input to an array. The input could be a lists, tuple, ndarray, etc.

Syntax:

numpy.asarray(data, dtype=None, order=None)[source]

Here,

data: Data that you want to convert to an array

dtype: This is an optional argument. If not specified, the data type is inferred from the input data

Order: Default is C which is an essential row style. Other option is F (Fortan-style)

Example:

Consider the following 2-D matrix with four rows and four columns filled by 1

import numpy as np
A = np.matrix(np.ones((4,4)))			

If you want to change the value of the matrix, you cannot. The reason is, it is not possible to change a copy.

np.array(A)[2]=2
print(A)			
[[1. 1. 1. 1.]
 [1. 1. 1. 1.] 
 [1. 1. 1. 1.] 
 [1. 1. 1. 1.]]

Matrix is immutable. You can use asarray if you want to add modification in the original array. Let's see if any change occurs when you want to change the value of the third rows with the value 2

np.asarray(A)[2]=2
print(A)

Code Explanation:

np.asarray(A): converts the matrix A to an array

[2]: select the third rows

Output:

[[1. 1. 1. 1.] 
      [1. 1. 1. 1.] 
      [2. 2. 2. 2.] # new value 
      [1. 1. 1. 1.]]

 

YOU MIGHT LIKE: