Introduction to Numpy
M3-R5.1 · Chapter 9: NumPy Basics · 4 min read
1. Introduction to NumPy
- Numpyis a python package which stands for “Numerical Python
- NumPy (Numerical Python) is the foundational library for scientific computing in Python.
- NumPywas created in 2005 by Travis Oliphant. It is an open source project and you can use it freely.
- It provides support for large, multi-dimensional arrays and matrices, along with a collection of high-level mathematical functions to operate on these arrays.
- It also has functions for working in domain of linear algebra, fourier transform, and matrices
1.1 Why NumPy?
Python lists are flexible but slow for numerical operations. NumPy arrays are:
- Faster — stored as contiguous memory blocks (C-style)
- Memory-efficient — all elements have the same datatype
- Vectorized — operations apply element-wise without loops
- Feature-rich — built-in functions for math, statistics, linear algebra
|
Feature |
Python List |
NumPy Array |
|
Speed |
Slow |
Fast |
|
Memory |
More |
Less |
|
Data Types |
Mixed allowed |
Same type only |
|
Math Functions |
Limited |
Extensive built-in |
1.2 Installing and Importing NumPy
If you have Python and PIP already installed on a system, then installation of NumPy is very easy. Install it using this command: Ø
C:\Users\Your Name>pip install numpy
If this command fails, then use a python distribution that already has NumPy installed like, Anaconda, Spyder etc.
Once NumPy is installed, import it in your applications by adding the import keyword:
import numpy
Now NumPy is imported and ready to use
import numpy
arr = numpy.array([1,2,3,4,5])
print(arr)
Alias Methos using as keyword----
import numpy as np
arr = numpy.array([1,2,3,4,5])
print(arr)
Note – In exams often ask about the standard alias used to import NumPy — always use 'np'.
2. Introduction to NumPy ndarray
The core object in NumPy is the ndarray (N-Dimensional Array).
It is a grid of values, all of the same type, indexed by a tuple of non-negative integers.
2.1 What is an ndarray?
- nd stands for N-Dimensional
- Homogeneous — all elements must be of the same type
- Fixed size at creation (unlike Python lists)
- Supports vectorized operations (no explicit loops needed)
2.2 Creating a Basic ndarray
import numpy as np
# 0D array (Scaler)
ar = np.array(66)
print(ar) # 66
# 1D array (Vector)
ar2 = np.array([1, 2, 3, 4, 5])
print(ar2) # [1 2 3 4 5]
# 2D array (Matrix)
ar3 = np.array([[1, 2, 3], [4, 5, 6]])
print(ar3)
# [[1 2 3]
# [4 5 6]]
# 3D array
c = np.array([[[1,2],[3,4]], [[5,6],[7,8]]])
print(c.ndim) # 3
Note - ndarray with 0 axis = 0D(Scaler) 1 axis = 1D (vector), 2 axes = 2D (matrix), 3+ axes = nd-array (tensor).