Skip to content

Numpy array reshape #698

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions contrib/numpy/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
- [Installing NumPy](installing-numpy.md)
- [Introduction](introduction.md)
- [NumPy Data Types](datatypes.md)
- [Numpy Array Shape and Reshape](reshape-array.md)
- [Basic Mathematics](basic_math.md)
- [Operations on Arrays in NumPy](operations-on-arrays.md)
- [Loading Arrays from Files](loading_arrays_from_files.md)
Expand Down
57 changes: 57 additions & 0 deletions contrib/numpy/reshape-array.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Numpy Array Shape and Reshape

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.

Let us create a 2D array

``` python
import numpy as np

numbers = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(numbers)
```

#### Output:

``` python
array([[1, 2, 3, 4],[5, 6, 7, 8]])
```

## Changing Array Shape using `reshape()`

The `reshape()` function allows you to rearrange the data within a NumPy array.

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.

``` python
arr_1d = np.array([1, 2, 3, 4, 5, 6]) # 1D array
arr_2d = arr_1d.reshape(2, 3) # Reshaping with 2 rows and 3 cols

print(arr_2d)
```

#### Output:

``` python
array([[1, 2, 3],[4, 5, 6]])
```

## Changing Array Shape using `resize()`

The `resize()` function allows you to modify the shape of a NumPy array directly.

It take 2 arguements, row and columns.

``` python
import numpy as np
arr_1d = np.array([1, 2, 3, 4, 5, 6])

arr_1d.resize((2, 3)) # 2 rows and 3 cols
print(arr_1d)
```

#### Output:

``` python
array([[1, 2, 3],[4, 5, 6]])
```