Instance analysis of Python numpy array replication

Time:2021-3-24

This article mainly introduces the use of Python numpy array replication instance parsing, the article through the example code is very detailed, for everyone’s study or work has a certain reference learning value, need friends can refer to

When using python, we often deal with arrays. Sometimes we copy them, sometimes we don’t. this is also the place that beginners are most likely to misunderstand

No copy at all

import numpy as np
a =  np.arange (12) #a is a sequence
B = a # no new object is created
Print ('a's shape is: ', a.shape) # output a's size
Is print ('b 'a? 'B is a) # AB is two names of the same object
b. Shape = 3,4 # change the shape of B
Print ('a's shape changes to:'a.shape) # A's shanpe also changes

Output results

The shape of a is: (12,)
Is B a? True
The shape of a becomes: (3, 4)

View or shallow copy

Different array objects can be classified into the same data, and the view method creates a new object that is the same as the original array

a = np.arange(12)
C = A. view () # create a C like a
Print ('shape of a when C is unchanged: ', a.shape) # output the size of A
Is print ('c 'a? ', c is a)
Print ('Is C based on a ', c.base is a)
c.shape = 3, 4
Print ('c changes a's shape to: ', a.shape)

Output results:

Is c a? False
Is C based on a
The shape of a is: (12,)
The shape of a is: (12,)

Deep copy

At this time, D is a copy of a, just a simple copy, there is no relationship between the two

a = np.arange(12)
D = A. copy () # build a C like a
Is print ('d 'a? ', d is a)
Print ('Is D Based on a ', d.base is a)

Output results:

Is d a? False
Is d based on a false

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.