pandas and NumPy 3 cheatsheet
pandas and NumPy 3: NumPy
10 common pandas and NumPy 3 tasks.
Create an array
Create an array from a list. Arrays hold one type and operate on all items at once.
a = np.array([1, 2, 3])
Create a range
Create evenly spaced values, either by step or by count.
np.arange(0, 10, 2)
np.linspace(0, 1, 5)
Create filled arrays
Create arrays of zeros, ones or a given value.
np.zeros((3, 4))
np.ones(5)
np.full((2, 2), 7)
Reshape an array
Change the shape without changing the data. -1 lets NumPy work out the size.
a.reshape(2, -1)
Generate random numbers
Use the modern generator with a seed so results can be reproduced.
rng = np.random.default_rng(42)
rng.normal(size=5)
rng.integers(0, 10, size=3)
Compute statistics along an axis
Average each column (axis 0) or each row (axis 1).
a.mean(axis=0)
a.std(axis=1)
a.sum()
Sort and find positions
Sort values, or get the indices that would sort them.
np.sort(a)
np.argsort(a)
Find distinct values
Get the sorted unique values and how often each occurs.
values, counts = np.unique(a, return_counts=True)