Python NumPy »

My Coding > Programming language > Python > Python libraries and packages > Python NumPy

Python NumPy (Page: 4)

Go to Page:

  1. NumPy creating;
  2. NumPy array reshaping;
  3. Images with NumPy;
  4. NumPy copy;
  5. NumPy mask;
  6. Geometry;

NumPy shallow copy (vew)

To make view of NumPy or "view" use method .view(). It will create view to the original array, or shallow copy. It will be a different structure but the elements will be the same.


import numpy as np
t1 = np.array([1, 2, 3, 4, 5, 6])
v1 = t1.view()

print("id, v1 =", id(v1), v1)          # id, v1 = 140499941424864 [1 2 3 4 5 6]
print("id, t1 =", id(t1), t1)          # id, t1 = 140499941424384 [1 2 3 4 5 6]
print("v1 is t1:", v1 is t1)           # False
print("v1.base is t1:", v1.base is t1) # True

v1[2]='33'

print("v1 =", v1)                      # v1 = [ 1  2 33  4  5  6]
print("t1 =", t1)                      # t1 = [ 1  2 33  4  5  6]

v1.shape = 2,3
print("v1 =", v1)                      # v1 = [[ 1  2 33] [ 4  5  6]]
print("t1 =", t1)                      # t1 = [ 1  2 33  4  5  6]

v1[1][0] = '44'
print("v1 =", v1)                      # v1 = [[ 1  2 33] [ 44  5  6]]
print("t1 =", t1)                      # t1 = [ 1  2 33  44  5  6]

NumPy deep copy

To make a proper, deep copy of NumPy arrray use methof .copy() - which is a bit different from copy.copy() method. This numpy.copy() method will create fully independent copy.


import numpy as np
t2 = np.array([1, 2, 3, 4, 5, 6])
v2 = t2.copy()
print("v2.base is t2:", v2.base is t2)         # False

v2[2] = 33

print("v2 =", v2)                              # v2 = [ 1  2 33  4  5  6]
print("t2 =", t2)                              # t2 = [ 1  2 3  4  5  6]

t3 = np.array([[1, 2], [3, 4], [5, 6]])
v3 = t3.copy()

v3[1][1] = 44

print("v3 =", v3)                              # v3 = [[ 1  2] [ 3 44] [ 5  6]]
print("t3 =", t3)                              # t3 = [[1 2] [3 4] [5 6]]

Go to Page: 1; 2; 3; 4; 5; 6;


Published: 2021-10-04 11:48:19
Updated: 2021-11-14 08:41:55

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.