Summary of 18 practical Numpy code fragments

Posted by jannoy on Wed, 15 Dec 2021 03:28:55 +0100

Numpy has long been a universal choice for Python developers to perform array operations. It is built based on C language, which makes it a fast and reliable choice to perform array operations, and it has become a necessary basic library for machine learning and data science.

In this article, I sorted out some fragments of NumPy code, which are often used in daily development.

1. Create array

import numpy as np

new_array = np.array([1,2,3])

print(new_array)

# Output[1 2 3]

2. Gets the shape, dimension, and size of the Numpy array

# shape
print(new_array.shape)

# dimensions
print(new_array.ndim)

# size
print(new_array.size)

# Output(3,)
1
3

3. View the types of elements in the Numpy array

array = np.arange(0,10,1)
print(array.dtype)

# Output
int64

4. Gets the occupied byte size of each element in the array

array = np.array([1,2])
print(array.itemsize)

# Output
8

5. Specify the type of array when creating

array = np.array([[1,2], [3,4]], dtype=complex)
array

# Output
array([[1.+0.j, 2.+0.j],
       [3.+0.j, 4.+0.j]])

6. Create an array using placeholders

# All zero array
array = np.zeros((3,4))
print(array)
print("---")

# All 1 array
array = np.ones((1,2))
print(array)
print("---")

# An empty array of shape (2,3) to randomly generate data
array = np.empty((2,3))
print(array)
print("---")

# Output
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
---
[[1. 1.]]
---
[[4.67280967e-310 0.00000000e+000 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000 0.00000000e+000]]
---

7. Create sequence

# Use NP Range creates a sequence of 0 to 42 elements in steps of 1
array = np.arange(0,42,1)
print(array)
print("---")

# Use NP Linspace inserts 42 elements between 0 and 100
array = np.linspace(0,100,42)
print(array)
print("---")

# Output
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41]
---
[  0.           2.43902439   4.87804878   7.31707317   9.75609756
  12.19512195  14.63414634  17.07317073  19.51219512  21.95121951
  24.3902439   26.82926829  29.26829268  31.70731707  34.14634146
  36.58536585  39.02439024  41.46341463  43.90243902  46.34146341
  48.7804878   51.2195122   53.65853659  56.09756098  58.53658537
  60.97560976  63.41463415  65.85365854  68.29268293  70.73170732
  73.17073171  75.6097561   78.04878049  80.48780488  82.92682927
  85.36585366  87.80487805  90.24390244  92.68292683  95.12195122
  97.56097561 100.        ]
---

8. Mathematical functions in Numpy

import numpy as np
import matplotlib.pyplot as plt

# sine function
x = np.linspace(0,2*np.pi, 100)
f = np.sin(x)
plt.figure(figsize=(15,7))
plt.subplot(1,3,1)
plt.plot(f, color="green")
plt.title("np.sin(x)")

# cosine function
f = np.cos(x)
plt.subplot(1,3,2)
plt.plot(f, color="blue")
plt.title("np.cos(x)")

# tangent function
f = np.tan(x)
plt.subplot(1,3,3)
plt.plot(f, color="red")
plt.title("np.tan(x)")
plt.show()

9. Create an array by executing a function on each coordinate

some_function = lambda x: np.cos(x)+1
array = np.fromfunction(some_function, (100,))
plt.figure(figsize=(15,7))
plt.plot(array, color="green")
plt.title("np.cos(x) +1")
plt.show()

10. Traverses all elements of the Numpy array

a = np.arange(0,23,1)
for i in a.flat:
    print(i)

    
# Output
0
1
2
...
22

11. Gets the lower bound of a floating point number

np.floor(10.5)

10.0

12. Use T ravel() flattens the array

array = np.full(shape=(5,5),fill_value=10)
print(array)
print("---")
print("Flattened array:")
print(array.ravel())

# Output

[[10 10 10 10 10]
 [10 10 10 10 10]
 [10 10 10 10 10]
 [10 10 10 10 10]
 [10 10 10 10 10]]
---
Flattened array:
[10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
 10]

13. Gets the transpose of an array

array = np.random.random((2,5))
print(array)
print(array.T)

[[0.18735704 0.22800582 0.02552177 0.93552346 0.20720663]
 [0.74303284 0.1897481  0.91389602 0.23099501 0.07565492]]
[[0.18735704 0.74303284]
 [0.22800582 0.1897481 ]
 [0.02552177 0.91389602]
 [0.93552346 0.23099501]
 [0.20720663 0.07565492]]

14. Use shape() and Reshape()

a = np.random.randint(100,size=(3,4))
print(a)
a_reshaped = np.reshape(a, (1,12))
print(a_reshaped)

# use. resize() method
a.resize((1,12))

# Output

[[29 18 39 24]
 [53 45 49  8]
 [90 75 61 61]]
[[29 18 39 24 53 45 49  8 90 75 61 61]]

15. Stack arrays along different axes

a = np.random.random((2,2))
print(a)
b = np.random.random((2,2))
print(b)

# Stack along vertical axis (get more rows)
print(np.vstack((a,b)))
print(np.vstack((a,b)).shape)

# Stack along horizontal axis (get more columns)
print(np.hstack((a,b)))
print(np.hstack((a,b)).shape)

# column_stack column overlay
print(np.column_stack((a,b)))

# Output
[[0.67028492 0.86322792]
 [0.38906266 0.36967583]]
[[0.51419553 0.21937852]
 [0.50375453 0.31634597]]
[[0.67028492 0.86322792]
 [0.38906266 0.36967583]
 [0.51419553 0.21937852]
 [0.50375453 0.31634597]]
(4, 2)
[[0.67028492 0.86322792 0.51419553 0.21937852]
 [0.38906266 0.36967583 0.50375453 0.31634597]]
(2, 4)
[[0.67028492 0.86322792 0.51419553 0.21937852]
 [0.38906266 0.36967583 0.50375453 0.31634597]]

16. Splits an array into smaller arrays

Use hsplit to split the original array along its horizontal axis by specifying the number of arrays of the same shape to return, or by specifying the column after the split should occur. vsplit is divided along the vertical axis in the same way as hsplit

# Split the array into 5 smaller arrays along the horizontal axis
a = np.arange(0, 5, 1)
print("Horizontal split")
print(np.hsplit(a, 5))
print("---")

# Split the array into five smaller arrays along the vertical axis
a = np.random.random((5,5))
print("Vertical split")
print(np.vsplit(a, 5))

Horizontal split
[array([0]), array([1]), array([2]), array([3]), array([4])]
---
Vertical split
[array([[0.69059321, 0.55703093, 0.20019592, 0.19697317, 0.37278251]]), array([[0.24597633, 0.87216661, 0.634432  , 0.35326185, 0.03130537]]), array([[0.18063077, 0.45045441, 0.06882852, 0.91273837, 0.07332161]]), array([[0.61738939, 0.11291748, 0.73152623, 0.49177006, 0.95750985]]), array([[0.90212777, 0.53825846, 0.86733505, 0.76165564, 0.17337721]])]

17. Shallow copy of array

. The view() method creates an object that is the same as the original array object. It creates a shallow copy of the array. The shallow copy only copies the pointer to an object, not the object data. The old and new objects still share the same piece of memory. Therefore, if one object changes the value of memory, it will affect the other object, that is, if the value of one object changes, the others will also change (using the same memory).

a = np.array([
    [0,1,2,3,4],
    [5,6,7,8,9],
    [10,11,12,13,14]
    ])

array_object = np.arange(0,10,1)

shallow_copy_object = array_object.view() # shallow copy

print("Array")
print(array_object)
print(f"Id = {id(array_object)}")
print("---")

print("Shallow Copy")
print(shallow_copy_object)
print(f"Id = {id(shallow_copy_object)}")
print("---")

shallow_copy_object[0] = 200

print("After assigment: shallow_copy_object[0] = 200")

print("Array")
print(array_object)

print("Shallow copy")
print(shallow_copy_object)

# Output

Array
[0 1 2 3 4 5 6 7 8 9]
Id = 139980496768528
---
Shallow Copy
[0 1 2 3 4 5 6 7 8 9]
Id = 139980496768720
---
After assigment: shallow_copy_object[0] = 200
Array
[200   1   2   3   4   5   6   7   8   9]
Shallow copy
[200   1   2   3   4   5   6   7   8   9]

18. Deep copy of array

The copy method copies a complete copy of an object and its data. A copy is completely copied, the internal element addresses are different, and the change of values will not affect each other.

array_object = np.arange(0, 23, 1)
deep_copy_object = array_object.copy()

print(deep_copy_object is array_object)

print("Array")
print(array_object)
print(f"Array id = {id(array_object)}")
print("---")
      
print("Deep Copy")
print(deep_copy_object)
print(f"Deep copy id = {id(deep_copy_object)}")
print("---")

deep_copy_object[0] = 234

print("After assignment: deep_copy_object[0] = 234")
print("Array")
print(array_object)
print("Deep copy")

print(deep_copy_object)

False
Array
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22]
Array id = 139980498767472
---
Deep Copy
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22]
Deep copy id = 139980496039824
---
After assignment: deep_copy_object[0] = 234
Array
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22]
Deep copy
[234   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
  18  19  20  21  22]

Author: Lucas Soares

Topics: Python Machine Learning Data Mining numpy