[Reproduced] Python Miscellaneous | (6) The difference between array() and asarray() in numpy

Reference link: numpy.asarray in Python

The array() and asarray() methods in numpy are very similar. Both of them can accept list or array type data as parameters. When their parameters are list data, there is no difference between the two; when their parameters are array types, np.array() will return a copy of the parameter array (copy, 2 have the same value but point to different memory), np.asarray() will return a view of the parameter array (two of them point to the same memory). 

The copy will open up a new piece of memory. For large arrays, there will be a large number of copy operations, which is slower and does not save memory; the view is equivalent to adding a new reference to the current memory, there is no copy operation, and the speed is faster and Save memory, but note that if you modify the data through one of the references, the other referenced data will also change because they point to the same memory area. 

table of Contents 

1. The parameter is a list 

2. The parameter is an array 

 

1. The parameter is a list 

import numpy as np

 

data = [[1,2,3],[4,5,6],[7,8,9]]

arr1 = np.array(data)

arr2 = np.asarray(data)

data[1][2] = 100

print(data)

print(arr1)

print(arr2)

 

 

2. The parameter is an array 

arr1 = np.random.randint (0.10, (3.4))

arr2 = np.array(arr1) #arr2 is a copy of arr1

arr3 = np.asarray(arr1) #arr3 is the view of arr1

arr1[1] = 1000 #Change arr1 arr2 does not change arr3 will follow

print(arr1)

print(arr2)

print(arr3)

print("-------------------") #Change arr3, arr1 will also change

arr3 [0] = -10000

print(arr1)

print(arr2)

print(arr3)

Guess you like

Origin blog.csdn.net/u013946150/article/details/113042032