NumPy - 2

import numpy as np
## Copy Vs View
arr = np.array([1,2,3,4,5])
myarray = arr.copy()
# myarray[0] = 42
arr[0] = 10
print('arr:', arr)
print('myarray:', myarray)
arr: [10  2  3  4  5]
myarray: [1 2 3 4 5]
arr = np.array([1,2,3,4,5])
myarray = arr.view()
myarray[0] = 40
arr[0] = 10
print('arr:', arr)
print('myarray:', myarray)
arr: [10  2  3  4  5]
myarray: [10  2  3  4  5]
print(myarray.base)
[10  2  3  4  5]
print(arr.base)
None
arr = np.array([1,2,3,4,5])
myarray = arr.copy()
print(myarray.base)
None
## Shape
arr = np.array(10)
print(arr.shape)
()
arr1 = np.array([1,2,3,4,5])
print(arr1.shape)
(5,)
arr2 = np.array([[1,2],[3,5]])
print(arr2.shape)
(2, 2)
arr3 = np.array([[[1,2,3],[4,5,6]], [[1,2,3],[4,5,6]]])
print(arr3.shape)
(2, 2, 3)
arrn = np.array([1,2,3], ndmin=5)
print(arrn)
print(arrn.shape)
[[[[[1 2 3]]]]]
(1, 1, 1, 1, 3)
## reshape
arr = np.array([[[1,2],[4,5]], [[1,2],[4,5]]])
print(arr)
[[[1 2]
  [4 5]]

 [[1 2]
  [4 5]]]
arr.reshape(2,4)
array([[1, 2, 4, 5],
       [1, 2, 4, 5]])
arr.reshape(3,4)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-65-6e762b0d3244> in <module>
----> 1 arr.reshape(3,4)

ValueError: cannot reshape array of size 8 into shape (3,4)
myarray = arr.reshape(8)
print(myarray)
[1 2 4 5 1 2 4 5]
print(myarray.base)
[[[1 2]
  [4 5]]

 [[1 2]
  [4 5]]]
arr.reshape(2,2,2)
array([[[1, 2],
        [4, 5]],

       [[1, 2],
        [4, 5]]])
arr.reshape(2,-1)
array([[1, 2, 4, 5],
       [1, 2, 4, 5]])
arr.reshape(-1,2,2)  ### (x * 2 * 2 = 8 =>  x = 2)
array([[[1, 2],
        [4, 5]],

       [[1, 2],
        [4, 5]]])
arr.reshape(-1)
array([1, 2, 4, 5, 1, 2, 4, 5])
## iterating arrays
myarray = np.array([1,2,3])
myarray2 = np.array([[1,2,3],[4,5,6]])
myarray3 = np.array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
for x in myarray:
    print(x)
1
2
3
for x in myarray2:
    print(x)
[1 2 3]
[4 5 6]
for x in myarray2:
    for y in x:
        print(y)
1
2
3
4
5
6
for x in myarray3:
    for y in x:
        print(y)
[1 2 3]
[4 5 6]
[1 2 3]
[4 5 6]
for x in myarray3:
    for y in x:
        for z in y:
            print(z)
1
2
3
4
5
6
1
2
3
4
5
6
for x in np.nditer(myarray3):
    print(x)
1
2
3
4
5
6
1
2
3
4
5
6
print(myarray2)
[[1 2 3]
 [4 5 6]]
for x in np.nditer(myarray2[ 1: , ::2]):
    print(x)
4
6
for idx, x in np.ndenumerate(myarray2):
    print(idx, x)
(0, 0) 1
(0, 1) 2
(0, 2) 3
(1, 0) 4
(1, 1) 5
(1, 2) 6
for idx, x in np.ndenumerate(myarray):
    print(idx, x)
(0,) 1
(1,) 2
(2,) 3
print(myarray3)
[[[1 2 3]
  [4 5 6]]

 [[1 2 3]
  [4 5 6]]]
for x in np.nditer(myarray3[:1,1:,::2]):
    print(x)
4
6
for idx, x in np.ndenumerate(myarray3):
    print(idx, x)
(0, 0, 0) 1
(0, 0, 1) 2
(0, 0, 2) 3
(0, 1, 0) 4
(0, 1, 1) 5
(0, 1, 2) 6
(1, 0, 0) 1
(1, 0, 1) 2
(1, 0, 2) 3
(1, 1, 0) 4
(1, 1, 1) 5
(1, 1, 2) 6