NumPy Basics: Arrays &
Operations
With Examples
Introduction to NumPy
NumPy stands for Numerical Python.
It is a fundamental library for scientific
computing in Python.
Provides support for large, multidimensional
arrays and matrices.
Includes mathematical, logical, and
statistical operations.
Creating NumPy Arrays
Example:
>>> import numpy as np
>>> arr = [Link]([1, 2, 3, 4])
>>> print(arr)
Output: [1 2 3 4]
[Link]() is used to create an array.
Arrays can be 1D, 2D, or multi-dimensional.
Array Attributes
>>> arr = [Link]([[1, 2, 3], [4, 5, 6]])
>>> [Link] # Returns dimensions (rows,
columns)
(2, 3)
>>> [Link] # Returns number of
dimensions
2
>>> [Link] # Returns total number of
elements
6
Array Operations
NumPy supports element-wise operations:
>>> a = [Link]([1, 2, 3])
>>> b = [Link]([4, 5, 6])
>>> a + b # Addition
array([5, 7, 9])
>>> a * b # Multiplication
array([ 4, 10, 18])
>>> a ** 2 # Power
array([1, 4, 9])
Useful NumPy Functions
[Link]((2,2)) → Creates array of zeros
[Link]((3,3)) → Creates array of ones
[Link](3) → Identity matrix
[Link](0,10,2) → [0 2 4 6 8]
[Link](0,1,5) → [0. , 0.25, 0.5 , 0.75, 1. ]
Array Indexing & Slicing
>>> arr = [Link]([10, 20, 30, 40, 50])
>>> arr[1:4]
array([20, 30, 40])
>>> arr[:3]
array([10, 20, 30])
>>> arr[-1]
50
Statistical & Math Functions
>>> arr = [Link]([1, 2, 3, 4, 5])
>>> [Link](arr)
3.0
>>> [Link](arr)
1.4142
>>> [Link](arr)
15
>>> [Link](arr), [Link](arr)
(5, 1)
Reshaping & Transpose
>>> arr = [Link]([[1, 2, 3], [4, 5, 6]])
>>> [Link](3, 2)
array([[1, 2], [3, 4], [5, 6]])
>>> arr.T # Transpose
array([[1, 4], [2, 5], [3, 6]])
Summary
NumPy is essential for numerical computing.
Arrays are more efficient than Python lists.
Supports element-wise operations and
broadcasting.
Includes many built-in functions for
mathematical and statistical tasks.