Numpy : Exploring the Basics

Samith FernandoSamith Fernando
2 min read

1. Introduction to NumPy

NumPy is a powerful Python library used for numerical computing, particularly with large, multi-dimensional arrays and matrices. It provides an extensive collection of functions and methods to perform mathematical and logical operations on these data structures.

2. Installing NumPy

Before using NumPy, you need to install it. This code block demonstrates how to install NumPy using pip, which is the standard package installer for Python.

pip install numpy

3. Creating NumPy Arrays

Creating arrays is a fundamental aspect of NumPy. Arrays are the building blocks for numerical operations in NumPy.

import numpy as np

# Create a 1D array
arr1d = np.array([1, 2, 3, 4, 5])
print("1D Array:")
print(arr1d)

# Create a 2D array
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("2D Array:")
print(arr2d)

In this block, we import NumPy as np and demonstrate how to create a 1D array and a 2D array using NumPy's array() function.

4. Array Attributes

NumPy arrays have various attributes that provide essential information about the array.

print("Shape of arr2d:", arr2d.shape)  # Shape of the array
print("Data type of arr2d:", arr2d.dtype)  # Data type of the array elements
print("Number of dimensions:", arr2d.ndim)  # Number of dimensions
print("Size of arr2d:", arr2d.size)  # Total number of elements in the array

Here, we showcase common array attributes such as shape, data type, number of dimensions, and total size.

5. Array Indexing and Slicing

NumPy arrays support indexing and slicing, enabling access to specific elements, rows, and columns.

print("Element at (1, 1):", arr2d[1, 1])  # Accessing a specific element
print("First row:", arr2d[0])             # Accessing a row
print("First column:", arr2d[:, 0])       # Accessing a column

Ill be explaining this in detail in another post

6. Array Operations

NumPy facilitates efficient element-wise operations and a wide range of mathematical functions.

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

print("a + b:", a + b)  # Addition
print("a * b:", a * b)  # Multiplication
print("sin(a):", np.sin(a))  # Trigonometric functions

7. Conclusion

This article provides an overview of NumPy's basic functionality. We've covered installation, array creation, attributes, indexing, and basic operations. NumPy is a fundamental tool for efficient numerical computation and data manipulation in Python. Future articles will delve into more advanced features and applications of NumPy.

0
Subscribe to my newsletter

Read articles from Samith Fernando directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Samith Fernando
Samith Fernando

Passionate about programming from a young age, especially with Arduino boards. Python enthusiast turned aspiring AI developer. 🤖✨ #AI #Python #Arduino