NumPy stands for Numerical Python. NumPy is a powerful Python library used for numerical computations.
NumPy was created in 2005 by Travis Oliphant for working with arrays.
import numpy as np
# Creating a NumPy array
arr = np.array([1, 2, 3, 4, 5])
print(arr)
NumPy is a Python library and is written partially in Python, but most of the parts that require fast computation are written in C or C++
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
The version string is stored under __version__ attribute.
You can test NumPy installation by running the following command in Python:
import numpy as np
print(np.__version__)
โ If You Face Any Problem Installing NumPy
๐ Watch this short video guide: ๐บ How to Install NumPy in Python
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will be converted into an ndarray:
Syntax: numpy.array(object, dtype=None, copy=True, order='K', ndmin=0)
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
NumPy arrays can have multiple dimensions depending on the data. Let's look at each:
๐น 0-D Array (Scalar) A single value (no dimension)
import numpy as np
arr0d = np.array(5)
print(arr0d)
๐น 1-D Array (Vector) A simple list of values
arr1d = np.array([10, 20, 30])
print(arr1d)
๐น 2-D Array (Matrix) Array of arrays โ like rows and columns
arr2d = np.array([[1, 2], [3, 4]])
print(arr2d)
3-D Array (Tensor) Array of 2D matrices
arr3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr3d)
๐ How to Check Number of Dimensions
print(arr3d.ndim)
| # | Point | Python List | NumPy Array |
|---|---|---|---|
| 1 | Change / Size | Dynamic โ can grow or shrink | Fixed size once created |
| 2 | Data Type | Can have mixed data types | Only one data type (homogeneous) |
| 3 | Memory | Uses more memory | More memory-efficient |
| 4 | Speed | Slower in numerical operations | Faster due to optimized C-based code |
After creating a NumPy array, you can check its key properties using built-in attributes.
| ๐ข Attribute | ๐ Description | ๐งช Example Output |
|---|---|---|
| arr.ndim | Number of dimensions | 2 |
| arr.shape | Shape of array (rows, columns) | (2, 3) |
| arr.size | Total number of elements | 6 |
| arr.dtype | Data type of elements | int64 |
| arr.itemsize | Size (in bytes) of each element | 8 |
| arr.nbytes | Total memory (bytes) consumed | 48 |
NumPy Array Creation Methods are used to create arrays in various ways โ such as from existing data, with fixed values, numerical ranges, or random values.
| ๐ Method | ๐ Description | ๐ Example |
|---|---|---|
| np.array() | Creates array from list, tuple, etc. | np.array([1, 2, 3]) |
| np.asarray() | Converts input to array | np.asarray((4, 5, 6)) |
| np.copy() | Creates a copy of an array | np.copy(a) |
| ๐ Method | ๐ Description | ๐ Example |
|---|---|---|
| np.zeros() | Creates array filled with 0s | np.zeros((2, 3)) |
| np.ones() | Creates array filled with 1s | np.ones((3,)) |
| np.full() | Filled with specified value | np.full((2, 2), 7) |
| np.empty() | Uninitialized array | np.empty((2, 2)) |
| ๐ Method | ๐ Description | ๐ Example |
|---|---|---|
| np.arange() | Evenly spaced values | np.arange(1, 10, 2) |
| np.linspace() | Even spacing over range | np.linspace(0, 1, 5) |
| np.logspace() | Logarithmic spacing | np.logspace(1, 3, 3) |
| ๐ Method | ๐ Description | ๐ Example |
|---|---|---|
| np.random.rand() | Random floats in [0, 1) | np.random.rand(2, 2) |
| np.random.randn() | Normal distribution | np.random.randn(3) |
| np.random.randint() | Random integers | np.random.randint(1, 10, 5) |
| np.random.random() | Random float array | np.random.random((2, 2)) |
| np.random.choice() | Random choice from list | np.random.choice([10, 20, 30]) |
Indexing means accessing individual elements in a NumPy array using their position (index).
import numpy as np
# 1D Array
a = np.array([10, 20, 30, 40, 50])
print("1D Array:", a)
print("a[2] =", a[2])
# 2D Array
b = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:\n", b)
print("b[1, 2] =", b[1, 2])
# 3D Array
c = np.array([
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
])
print("\n3D Array:\n", c)
print("c[1, 0, 1] =", c[1, 0, 1])
Slicing means accessing a group (range) of elements from the array using a specific pattern or range of indices.
Syntax: array[start : stop : step]
import numpy as np
# 1D Array
a = np.array([10, 20, 30, 40, 50])
print("1D Array:", a)
print("a[1:4] =>", a[1:4]) # Output: [20 30 40]
print("a[::2] =>", a[::2]) # Output: [10 30 50]
# 2D Array
b = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print("\n2D Array:\n", b)
print("b[0:2, 1:] =>\n", b[0:2, 1:]) # Output: [[2 3] [5 6]]
print("b[:, ::2] =>\n", b[:, ::2]) # Output: [[1 3] [4 6] [7 9]]
# 3D Array
c = np.array([
[[11, 12], [13, 14]],
[[15, 16], [17, 18]]
])
print("\n3D Array:\n", c)
print("c[0, :, :] =>\n", c[0, :, :]) # First block
print("c[:, 1, :] =>\n", c[:, 1, :]) # Second row from each block
print("c[:, :, 1] =>\n", c[:, :, 1]) # Second column from each block
In NumPy, joining means combining two or more arrays into one. This can be done using several functions.
| ๐ Method | ๐ Description | ๐ Example | ๐ก Output |
|---|---|---|---|
| np.concatenate() | Join arrays along an existing axis | np.concatenate(([1, 2], [3, 4])) | [1 2 3 4] |
| np.hstack() | Stack arrays horizontally | np.hstack((a, b)) | [1 2 3 4] |
| np.vstack() | Stack arrays vertically | np.vstack((a, b)) | [[1 2] [3 4]] |
import numpy as np
# Define two 1D arrays
a = np.array([1, 2])
b = np.array([3, 4])
# 1. np.concatenate() โ join arrays along existing axis
c1 = np.concatenate((a, b))
print("concatenate:", c1) # Output: [1 2 3 4]
# 2. np.hstack() โ stack arrays horizontally (like concatenate for 1D)
c2 = np.hstack((a, b))
print("hstack: ", c2) # Output: [1 2 3 4]
# 3. np.vstack() โ stack arrays vertically (row-wise)
c3 = np.vstack((a, b))
print("vstack: \n", c3)
# Output:
# [[1 2]
# [3 4]]
Splitting means dividing a NumPy array into multiple smaller arrays. You can split arrays either equally or at specific positions.
| ๐ Method | ๐ Description | ๐ Example | ๐ก Output |
|---|---|---|---|
| np.split() | Split array into equal parts | np.split(arr, 3) |
Splits into 3 equal sub-arrays |
| np.array_split() | Split array into parts, unequal allowed | np.array_split(arr, 4) |
Splits into 4 parts, unequal if needed |
| np.hsplit() | Split array horizontally (by columns) | np.hsplit(arr, 2) |
Splits 2D array by columns |
| np.vsplit() | Split array vertically (by rows) | np.vsplit(arr, 2) |
Splits 2D array by rows |
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60])
# Equal split into 3 parts
print("np.split:", np.split(arr, 3))
# Unequal split into 4 parts
print("np.array_split:", np.array_split(arr, 4))
# 2D array for hsplit and vsplit
arr2d = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]])
# Horizontal split (by columns)
print("np.hsplit:", np.hsplit(arr2d, 2))
# Vertical split (by rows)
print("np.vsplit:", np.vsplit(arr2d, 2))
| ๐ Operation | ๐ Description | ๐ Example | ๐ก Output |
|---|---|---|---|
| Addition (+) | Element-wise addition | np.array([1,2]) + np.array([3,4]) |
[4 6] |
| Subtraction (-) | Element-wise subtraction | np.array([5,6]) - np.array([1,2]) |
[4 4] |
| Multiplication (*) | Element-wise multiplication | np.array([2,3]) * np.array([4,5]) |
[8 15] |
| Division (/) | Element-wise division | np.array([10,20]) / np.array([2,5]) |
[5. 4.] |
| Addition | Adds scalar to each element | np.array([1,2,3]) + 5 |
[6 7 8] |
| Subtraction | Subtracts scalar from each element | np.array([1,2,3]) - 2 |
[-1 0 1] |
| Multiplication | Multiplies each element by scalar | np.array([1,2,3]) * 3 |
[3 6 9] |
| Division | Divides each element by scalar | np.array([2,4,6]) / 2 |
[1. 2. 3.] |
| Floor Division | Divides and floors each element | np.array([5,7,9]) // 2 |
[2 3 4] |
| Modulus | Remainder of division for each element | np.array([5,7,9]) % 3 |
[2 1 0] |
| Power | Raises each element to scalar power | np.array([2,3,4]) ** 2 |
[4 9 16] |