Skip to content

Commit ed9e065

Browse files
committed
Numpy array reshape() is added
1 parent 9f0f50f commit ed9e065

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

contrib/numpy/array_reshape.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Numpy Array Shape and Reshape
2+
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+
Code to create a 2D array
5+
``` python
6+
import numpy as np
7+
8+
numbers = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
9+
print(numbers)
10+
11+
# Output:
12+
# array([[1, 2, 3, 4],[5, 6, 7, 8]])
13+
```
14+
15+
## Changing Array Shape using Reshape()
16+
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.
18+
19+
``` python
20+
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
22+
23+
print(arr_2d)
24+
25+
# Output:
26+
# array([[1, 2, 3],[4, 5, 6]])
27+
28+
```
29+
30+
## Changing Array Shape using Resize()
31+
The `resize()` function allows you to modify the shape of a NumPy array directly.
32+
It take 2 arguements, row and columns.
33+
34+
``` python
35+
import numpy as np
36+
arr_1d = np.array([1, 2, 3, 4, 5, 6])
37+
38+
arr_1d.resize((2, 3)) # 2rows and 3cols
39+
print(arr_1d)
40+
41+
# Output:
42+
# array([[1, 2, 3],[4, 5, 6]])
43+
44+
```
45+
46+
## Reshape() VS Resize()
47+
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)) |

0 commit comments

Comments
 (0)