This document explains how to create, index, slice, and perform operations on 2D Numpy arrays, including matrix addition, scalar multiplication, Hadamard product, and matrix multiplication.
This document covers the creation and manipulation of two-dimensional Numpy arrays, including indexing, slicing, matrix addition, scalar multiplication, Hadamard product, and matrix multiplication. Readers will learn practical techniques for working with 2D data structures in Python.
Numpy supports arrays with more than one dimension. Two-dimensional arrays are commonly used to represent matrices and tabular data. Arrays are created by casting nested lists to Numpy arrays.
1import numpy as np
2lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
3a = np.array(lst)
Key attributes:
| Attribute | Description |
|---|---|
| ndim | Number of dimensions (axes) |
| shape | Tuple of rows and columns |
| size | Total number of elements |
Elements are accessed using row and column indices:
1a[1, 2] # Second row, third column
2a[0, 1] # First row, second column
Slicing extracts subarrays:
1a[0, :2] # First row, first two columns
2a[:2, -1] # First two rows, last column
Matrix addition adds corresponding elements:
1X = np.array([[1, 2], [3, 4]])
2Y = np.array([[5, 6], [7, 8]])
3Z = X + Y # Matrix addition
Scalar multiplication multiplies every element:
1Z = Y * 2 # Scalar multiplication
Hadamard product multiplies elements in the same position:
1Z = X * Y # Hadamard product
Matrix multiplication uses the dot product:
1A = np.array([[1, 0, 2], [0, 1, 2]])
2B = np.array([[0, 2], [1, 2], [2, 1]])
3C = np.dot(A, B) # Matrix multiplication
Two-dimensional Numpy arrays provide a flexible and efficient way to represent and manipulate tabular and matrix data. Operations such as indexing, slicing, addition, scalar multiplication, Hadamard product, and matrix multiplication are essential for scientific computing and data analysis.
(2) The shape attribute returns a tuple representing the number of rows and columns in a 2D array.
(1) For matrix multiplication, the number of columns in the first matrix must equal the number of rows in the second.
(3) Hadamard product is performed using the * operator, not the dot function.
| Concept | Description |
|---|---|
| A. Indexing | 1. Extracts subarrays using row and column indices |
| B. Slicing | 2. Accesses elements using row and column positions |
| C. Matrix addition | 3. Adds corresponding elements of two arrays |
| D. Scalar multiplication | 4. Multiplies every element by a constant |
A-2, B-1, C-3, D-4.
Matrix multiplication in Numpy is performed using the dot function, not the * operator.
True. The dot function is used for matrix multiplication, while * performs element-wise multiplication.
(1) The correct syntax is a[1, 2].