2024-05-30 14:25:02 +00:00
# Numpy Array Shape and Reshape
2024-05-31 01:49:32 +00:00
2024-05-30 14:25:02 +00:00
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.
2024-05-31 01:49:32 +00:00
Let us create a 2D array
2024-05-30 14:25:02 +00:00
``` python
import numpy as np
numbers = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(numbers)
2024-05-31 01:49:32 +00:00
```
#### Output:
2024-05-30 14:25:02 +00:00
2024-05-31 01:49:32 +00:00
``` python
array([[1, 2, 3, 4],[5, 6, 7, 8]])
2024-05-30 14:25:02 +00:00
```
2024-05-31 01:49:32 +00:00
## Changing Array Shape using `reshape()`
2024-05-30 14:25:02 +00:00
The `reshape()` function allows you to rearrange the data within a NumPy array.
2024-05-31 01:49:32 +00:00
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.
2024-05-30 14:25:02 +00:00
``` python
arr_1d = np.array([1, 2, 3, 4, 5, 6]) # 1D array
2024-05-31 01:49:32 +00:00
arr_2d = arr_1d.reshape(2, 3) # Reshaping with 2 rows and 3 cols
2024-05-30 14:25:02 +00:00
print(arr_2d)
2024-05-31 01:49:32 +00:00
```
2024-05-30 14:25:02 +00:00
2024-05-31 01:49:32 +00:00
#### Output:
2024-05-30 14:25:02 +00:00
2024-05-31 01:49:32 +00:00
``` python
array([[1, 2, 3],[4, 5, 6]])
2024-05-30 14:25:02 +00:00
```
2024-05-31 01:49:32 +00:00
## Changing Array Shape using `resize()`
2024-05-30 14:25:02 +00:00
The `resize()` function allows you to modify the shape of a NumPy array directly.
2024-05-31 01:49:32 +00:00
2024-05-30 14:25:02 +00:00
It take 2 arguements, row and columns.
``` python
import numpy as np
arr_1d = np.array([1, 2, 3, 4, 5, 6])
2024-05-31 01:49:32 +00:00
arr_1d.resize((2, 3)) # 2 rows and 3 cols
2024-05-30 14:25:02 +00:00
print(arr_1d)
```
2024-05-31 01:49:32 +00:00
#### Output:
2024-05-30 14:25:02 +00:00
2024-05-31 01:49:32 +00:00
``` python
array([[1, 2, 3],[4, 5, 6]])
```