# Creating and Shaping Arrays — NumPy / Pandas / scikit-learn

Source: https://www.skillbyai.com/en/numpy-pandas-sklearn/a-create

> dtype, shape, reshape.

## The ndarray

A NumPy **ndarray** is a grid of values that all share one **dtype** (int64, float64, float32, bool), described by a **shape** tuple. Because the values are packed tightly in memory, operations on whole arrays run in optimised C instead of the Python interpreter. Create arrays from lists (`np.array`), with constructors (`zeros`, `ones`, `arange`, `linspace`), or from files and other libraries. `reshape` changes the shape without copying data when it can.

## One type, many dimensions

NumPy arrays store numbers of one type in contiguous memory, so whole-array operations run in compiled code.

![Three ideas: creating arrays, broadcasting, indexing.](assets/figures/numpy-pandas-sklearn/section-1-map.svg) — Figure 1.1 — Arrays, broadcasting and indexing.

## Creating, reshaping and choosing dtypes, run

I ran this with Python 3.12.3 and NumPy 2.5.3. The integer list becomes int64; reshape gives a 2 by 3 matrix; arange uses a step while linspace includes both ends; a float32 array of three values uses 12 bytes.

```python
import numpy as np

a = np.array([1, 2, 3, 4, 5, 6])
print(a, a.dtype, a.shape)
m = a.reshape(2, 3)
print(m)
print("shape:", m.shape, "ndim:", m.ndim, "size:", m.size)
print(np.zeros((2, 2)))
print(np.arange(0, 1, 0.25))
print(np.linspace(0, 1, 5))
f = np.array([1, 2, 3], dtype=np.float32)
print(f.dtype, f.nbytes, "bytes")
```

Output:

```
[1 2 3 4 5 6] int64 (6,)
[[1 2 3]
 [4 5 6]]
shape: (2, 3) ndim: 2 size: 6
[[0. 0.]
 [0. 0.]]
[0.   0.25 0.5  0.75]
[0.   0.25 0.5  0.75 1.  ]
float32 12 bytes
```

## An egg tray, not a shopping bag

A Python list is a bag that can hold anything, each item stored separately. An array is an egg tray: identical slots in a fixed grid, so you can process the whole tray at once.

**Quiz:** What do all elements of a NumPy array share?

- [ ] A Python object type per element
- [ ] A single value
- [x] A single dtype
- [ ] Nothing in particular

*Answer:* A single dtype. One dtype enables fast, compact storage.
