---
jupytext:
  formats: content_md///md:myst,content///ipynb
  text_representation:
    extension: .md
    format_name: myst
    format_version: 0.13
    jupytext_version: 1.13.8
kernelspec:
  display_name: Python 3 (ipykernel)
  language: python
  name: python3
---

(managing-data:numpy:array-manipulation-functions)=
# Array Manipulation Functions

NumPy comes with lots of functions for manipulating arrays. Some of them are needed more often, others almost never.
A comprehensive list is provided in [array manipulation routines](https://numpy.org/doc/stable/reference/routines.array-manipulation.html).
Here we only mention some of the more important ones.

```{code-cell} ipython3
import numpy as np
```

## Modifying Shape with `reshape`

A NumPy array's [`reshape`](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html) method yields an array of different shape, but with identical data. The new array has to have the same number of elements as the old one.

```{code-cell} ipython3
a = np.ones(5)         # 1d (vector)
b = a.reshape(1, 5)    # 2d (row matrix)
c = a.reshape(5, 1)    # 2d (column matrix)

print(a, '\n')
print(b, '\n')
print(c)
```

One dimension may be replaced by `-1` indicating that the size of this dimension shall be computed by NumPy:

```{code-cell} ipython3
a = np.ones((8, 8))
b = a.reshape(4, -1)

print(a.shape, b.shape)
```

## Mirrowing with `fliplr` and `flipud`

To mirrow a 2d array on its vertical or horizontal axis use [`fliplr`](https://numpy.org/doc/stable/reference/generated/numpy.fliplr.html) and [`flipud`](https://numpy.org/doc/stable/reference/generated/numpy.flipud.html), respectively.

```{code-cell} ipython3
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.fliplr(a)

print(a, '\n')
print(b)
```

## Joining Arrays with `concatenate` and `stack`

Arrays of identical shape (except for one axis) may be joined along an existing axis to one large array with [`concatenate`](https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html).

```{code-cell} ipython3
a = np.ones((2, 3))
b = np.zeros((2, 5))
c = np.full((2, 2), 5)
d = np.concatenate((a, b, c), axis=1)

print(d)
```

If identically shaped array shall be joined along a new axis, use [`stack`](https://numpy.org/doc/stable/reference/generated/numpy.stack.html).

```{code-cell} ipython3
a = np.ones(2)
b = np.zeros(2)
c = np.full(2, 5)
d = np.stack((a, b, c), axis=1)

print(d)
```

## Appending Data with `append`

Like Python lists NumPy arrays may be extended by appending further data. The [`append`](https://numpy.org/doc/stable/reference/generated/numpy.append.html) method takes the original array and the new data and returns the extended array.

```{code-cell} ipython3
a = np.ones((3, 3))
b = np.append(a, [[1, 2, 3]], axis=0)

print(b)
```
