NumPy

Akalanka Fernando
2 min readJul 12, 2024

--

To indicate the feeling of happiness when coding.
Photo by Markus Spiske on Unsplash

Summarizing my knowledge of learning NumPy as a stepping stone to Python coding!

NumPy is a powerful library in Python used for numerical computations. It provides support for arrays, matrices, and many mathematical functions to operate on these data structures.

So let’s derive into the basic usage.

Importing NumPy

import numpy as np

Creating Arrays

From a list

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

Zeros, Ones, and Empty arrays

b = np.zeros((2, 2))
c = np.ones((3, 3))
d = np.empty((2, 3))

Array Operations

Basic operations

# Adds 2 to each element in the array
e = a + 2
# Multiplies each element by 3
f = a * 3
# Squares each element
g = a ** 2

Element-wise operations

h = a + np.array([4, 5, 6])

Matrix multiplication

i = np.dot(np.array([[1, 2], [3, 4]]), np.array([[5, 6], [7, 8]]))

Slicing and Indexing

Indexing

# Accesses the second element
j = a[1]

Slicing

# Accesses the first two elements
k = a[0:2]

Reshaping Arrays

l = np.array([[1, 2, 3], [4, 5, 6]])
m = l.reshape((3, 2))

Aggregation Functions

Sum, Mean, Min, Max

n = np.sum(a)
o = np.mean(a)
p = np.min(a)
q = np.max(a)

Example-

Let’s create an array and perform some basic operations.

import numpy as np

# Creating an array
a = np.array([1, 2, 3, 4, 5])

# Adding 5 to each element
b = a + 5

# Multiplying each element by 2
c = a * 2

# Summing all elements
d = np.sum(a)

print("Original array:", a)
print("After adding 5:", b)
print("After multiplying by 2:", c)
print("Sum of all elements:", d)

--

--

Akalanka Fernando
Akalanka Fernando

Written by Akalanka Fernando

Get down to brass tacks on matters of technology!

No responses yet