Home  >  Article  >  Backend Development  >  The difference between array and asarray in numpy

The difference between array and asarray in numpy

不言
不言Original
2018-04-17 11:48:553378browse

The following is a detailed explanation of the difference between array and asarray in numpy. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together

Both array and asarray can convert structural data into ndarray, but the main difference is that when the data source is ndarray, array will still copy a copy and occupy new memory, but asarray does not meeting.

Example:

##

import numpy as np 
 
#example 1: 
data1=[[1,1,1],[1,1,1],[1,1,1]] 
arr2=np.array(data1) 
arr3=np.asarray(data1) 
data1[1][1]=2 
print 'data1:\n',data1 
print 'arr2:\n',arr2 
print 'arr3:\n',arr3

Output:

data1: 
[[1, 1, 1], [1, 2, 1], [1, 1, 1]] 
arr2: 
[[1 1 1] 
 [1 1 1] 
 [1 1 1]] 
arr3: 
[[1 1 1] 
 [1 1 1] 
 [1 1 1]]

It can be seen that there is no difference between array and asarray, both of which copy the metadata.

import numpy as np 
 
#example 2: 
arr1=np.ones((3,3)) 
arr2=np.array(arr1) 
arr3=np.asarray(arr1) 
arr1[1]=2 
print 'arr1:\n',arr1 
print 'arr2:\n',arr2 
print 'arr3:\n',arr3

Output:

arr1: 
[[ 1. 1. 1.] 
 [ 2. 2. 2.] 
 [ 1. 1. 1.]] 
arr2: 
[[ 1. 1. 1.] 
 [ 1. 1. 1.] 
 [ 1. 1. 1.]] 
arr3: 
[[ 1. 1. 1.] 
 [ 2. 2. 2.] 
 [ 1. 1. 1.]]

The difference between the two is only shown at this time

Related recommendations:


How to process Boolean arrays in numpy

Detailed explanation based on the difference between numpy.random.randn() and rand()


The above is the detailed content of The difference between array and asarray in numpy. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn