143. Multi-dimensional Arrays with numpy
Numpy is a powerful library in Python used for handling multi-dimensional arrays and performing mathematical operations on them. It provides efficient ways to work with large datasets and enables scientific computing tasks, such as matrix manipulation, linear algebra, statistics, and more.
Here are 10 Python code snippets demonstrating how to work with multi-dimensional arrays using numpy.
1. Creating a 2D Array
Creating a basic 2D (matrix-like) array using numpy.array().
Copy
import numpy as np
# Creating a 2x3 matrix (2D array)
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)Output:
Copy
[[1 2 3]
[4 5 6]]Explanation:
np.array()creates a 2D array with the provided nested list.
2. Creating an Array of Zeros
Creating a 2D array filled with zeros.
Copy
Output:
Copy
Explanation:
np.zeros()creates a multi-dimensional array of the given shape filled with zeros.
3. Creating an Array of Ones
Creating a 3x3 array filled with ones.
Copy
Output:
Copy
Explanation:
np.ones()creates a multi-dimensional array of the given shape filled with ones.
4. Reshaping Arrays
Changing the shape of an existing array.
Copy
Output:
Copy
Explanation:
reshape()is used to change the shape of the array without changing its data.
5. Indexing and Slicing in 2D Arrays
Accessing elements and slicing rows and columns.
Copy
Output:
Copy
Explanation:
Use array indexing (
arr[row, col]) to access specific elements.Use slicing to access rows (
arr[row]) and columns (arr[:, col]).
6. Array Transposition
Transposing a 2D array to flip rows and columns.
Copy
Output:
Copy
Explanation:
.Tis a shorthand to transpose the matrix, swapping rows and columns.
7. Element-wise Operations
Performing element-wise addition and multiplication on two arrays.
Copy
Output:
Copy
Explanation:
Numpy automatically performs element-wise addition and multiplication for arrays of the same shape.
8. Matrix Multiplication
Performing matrix multiplication using np.dot() or @.
Copy
Output:
Copy
Explanation:
np.dot()or@performs matrix multiplication on two arrays (if they satisfy matrix multiplication conditions).
9. Broadcasting
Using broadcasting to perform element-wise operations on arrays of different shapes.
Copy
Output:
Copy
Explanation:
Broadcasting allows operations between arrays of different shapes, where smaller arrays are automatically expanded to match the larger array's shape.
10. Calculating the Mean, Sum, and Standard Deviation
Performing statistical operations on multi-dimensional arrays.
Copy
Output:
Copy
Explanation:
Numpy provides easy-to-use functions like
np.mean(),np.sum(), andnp.std()to compute statistical metrics on arrays.
Conclusion:
Using numpy, you can efficiently create and manipulate multi-dimensional arrays, perform mathematical operations, and work with large datasets. These functionalities are highly optimized for performance, making numpy an essential library for scientific computing and data analysis in Python.
Last updated