|
| 1 | +# Numpy Array Shape and Reshape |
| 2 | + |
| 3 | +In NumPy, the primary data structure is the ndarray (N-dimensional array). An array can have one or more dimensions, and it organizes your data efficiently. |
| 4 | + |
| 5 | +Let us create a 2D array |
| 6 | + |
| 7 | +``` python |
| 8 | +import numpy as np |
| 9 | + |
| 10 | +numbers = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) |
| 11 | +print(numbers) |
| 12 | +``` |
| 13 | + |
| 14 | +#### Output: |
| 15 | + |
| 16 | +``` python |
| 17 | +array([[1, 2, 3, 4],[5, 6, 7, 8]]) |
| 18 | +``` |
| 19 | + |
| 20 | +## Changing Array Shape using `reshape()` |
| 21 | + |
| 22 | +The `reshape()` function allows you to rearrange the data within a NumPy array. |
| 23 | + |
| 24 | +It take 2 arguments, row and columns. The `reshape()` can add or remove the dimensions. For instance, array can convert a 1D array into a 2D array or vice versa. |
| 25 | + |
| 26 | +``` python |
| 27 | +arr_1d = np.array([1, 2, 3, 4, 5, 6]) # 1D array |
| 28 | +arr_2d = arr_1d.reshape(2, 3) # Reshaping with 2 rows and 3 cols |
| 29 | + |
| 30 | +print(arr_2d) |
| 31 | +``` |
| 32 | + |
| 33 | +#### Output: |
| 34 | + |
| 35 | +``` python |
| 36 | +array([[1, 2, 3],[4, 5, 6]]) |
| 37 | +``` |
| 38 | + |
| 39 | +## Changing Array Shape using `resize()` |
| 40 | + |
| 41 | +The `resize()` function allows you to modify the shape of a NumPy array directly. |
| 42 | + |
| 43 | +It take 2 arguements, row and columns. |
| 44 | + |
| 45 | +``` python |
| 46 | +import numpy as np |
| 47 | +arr_1d = np.array([1, 2, 3, 4, 5, 6]) |
| 48 | + |
| 49 | +arr_1d.resize((2, 3)) # 2 rows and 3 cols |
| 50 | +print(arr_1d) |
| 51 | +``` |
| 52 | + |
| 53 | +#### Output: |
| 54 | + |
| 55 | +``` python |
| 56 | +array([[1, 2, 3],[4, 5, 6]]) |
| 57 | +``` |
0 commit comments