|
1 | 1 | # Numpy Array Shape and Reshape
|
| 2 | + |
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.
|
3 | 4 |
|
4 |
| -Code to create a 2D array |
| 5 | +Let us create a 2D array |
| 6 | + |
5 | 7 | ``` python
|
6 | 8 | import numpy as np
|
7 | 9 |
|
8 | 10 | numbers = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
|
9 | 11 | print(numbers)
|
| 12 | +``` |
| 13 | + |
| 14 | +#### Output: |
10 | 15 |
|
11 |
| -# Output: |
12 |
| -# array([[1, 2, 3, 4],[5, 6, 7, 8]]) |
| 16 | +``` python |
| 17 | +array([[1, 2, 3, 4],[5, 6, 7, 8]]) |
13 | 18 | ```
|
14 | 19 |
|
15 |
| -## Changing Array Shape using Reshape() |
| 20 | +## Changing Array Shape using `reshape()` |
| 21 | + |
16 | 22 | The `reshape()` function allows you to rearrange the data within a NumPy array.
|
17 |
| -It take 2 arguements, 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. |
| 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. |
18 | 25 |
|
19 | 26 | ``` python
|
20 | 27 | arr_1d = np.array([1, 2, 3, 4, 5, 6]) # 1D array
|
21 |
| -arr_2d = arr_1d.reshape(2, 3) # Reshaping with 2rows and 3cols |
| 28 | +arr_2d = arr_1d.reshape(2, 3) # Reshaping with 2 rows and 3 cols |
22 | 29 |
|
23 | 30 | print(arr_2d)
|
| 31 | +``` |
24 | 32 |
|
25 |
| -# Output: |
26 |
| -# array([[1, 2, 3],[4, 5, 6]]) |
| 33 | +#### Output: |
27 | 34 |
|
| 35 | +``` python |
| 36 | +array([[1, 2, 3],[4, 5, 6]]) |
28 | 37 | ```
|
29 | 38 |
|
30 |
| -## Changing Array Shape using Resize() |
| 39 | +## Changing Array Shape using `resize()` |
| 40 | + |
31 | 41 | The `resize()` function allows you to modify the shape of a NumPy array directly.
|
| 42 | + |
32 | 43 | It take 2 arguements, row and columns.
|
33 | 44 |
|
34 | 45 | ``` python
|
35 | 46 | import numpy as np
|
36 | 47 | arr_1d = np.array([1, 2, 3, 4, 5, 6])
|
37 | 48 |
|
38 |
| -arr_1d.resize((2, 3)) # 2rows and 3cols |
| 49 | +arr_1d.resize((2, 3)) # 2 rows and 3 cols |
39 | 50 | print(arr_1d)
|
40 |
| - |
41 |
| -# Output: |
42 |
| -# array([[1, 2, 3],[4, 5, 6]]) |
43 |
| - |
44 | 51 | ```
|
45 | 52 |
|
46 |
| -## Reshape() VS Resize() |
| 53 | +#### Output: |
47 | 54 |
|
48 |
| -| Reshape | Resize | |
49 |
| -| ----------- | ----------- | |
50 |
| -| Does not modify the original array | Modifies the original array in-place | |
51 |
| -| Creates a new array | Changes the shape of the array | |
52 |
| -| Returns a reshaped array | Doesn't return anything | |
53 |
| -| Compatibility between dimensions | Does not compatibility between dimensions | |
54 |
| -| Syntax: reshape(row,col) | Syntax: resize((row,col)) | |
| 55 | +``` python |
| 56 | +array([[1, 2, 3],[4, 5, 6]]) |
| 57 | +``` |
0 commit comments