NumPy: manipulating numerical data

This notebook is part of the \(\omega radlib\) documentation: https://docs.wradlib.org.

Copyright (c) \(\omega radlib\) developers. Distributed under the MIT License. See LICENSE.txt for more info.

NumPy: manipulating numerical data#

NumPy is the key Python package for creating and manipulating (multi-dimensional) numerical arrays. NumPy arrays are also the most important data objects in \(\omega radlib\). It has become a convention to import NumPy as follows:

import numpy as np

Creating and inspecting NumPy arrays#

The ndarray, a numerical array, is the most important data type in NumPy.

a = np.array([0, 1, 2, 3])
print(a)
print(type(a))
[0 1 2 3]
<class 'numpy.ndarray'>

Inspect the shape (i.e. the number and size of the dimensions of an array).

print(a.shape)
# This creates a 2-dimensional array
a2 = np.array([[0, 1], [2, 3]])
print(a2.shape)
(4,)
(2, 2)

There are various ways to create arrays: from lists (as above), using convenience functions, or from file.

# From lists
a = np.array([0, 1, 2, 3])
print(f"a looks like:\n{a}\n")

# Convenience functions
b = np.ones(shape=(2, 3))
print(f"b looks like:\n{b}\nand has shape {b.shape}\n")

c = np.zeros(shape=(2, 1))
print(f"c looks like:\n{c}\nand has shape {c.shape}\n")

d = np.arange(2, 10)
print(f"d looks like:\n{d}\nand has shape {d.shape}\n")

e = np.linspace(0, 10, 5)
print(f"e looks like:\n{e}\nand has shape {e.shape}\n")
a looks like:
[0 1 2 3]

b looks like:
[[1. 1. 1.]
 [1. 1. 1.]]
and has shape (2, 3)

c looks like:
[[0.]
 [0.]]
and has shape (2, 1)

d looks like:
[2 3 4 5 6 7 8 9]
and has shape (8,)

e looks like:
[ 0.   2.5  5.   7.5 10. ]
and has shape (5,)

You can change the shape of an array without changing its size.

a = np.arange(10)
b = np.reshape(a, (2, 5))
print(f"Array a has shape {a.shape}.\nArray b has shape {b.shape}")
Array a has shape (10,).
Array b has shape (2, 5)

Indexing and slicing#

You can index an ndarray in the same way as a list:

a = np.arange(10)
print(a)
print(a[0], a[2], a[-1])
[0 1 2 3 4 5 6 7 8 9]
0 2 9

Just follow your intuition for indexing multi-dimensional arrays:

a = np.diag(np.arange(3))
print(a, end="\n\n")

print(f"Second row, second column: {a[1, 1]}\n")

# Setting an array item
a[2, 1] = 10  # third line, second column
print(a, end="\n\n")

# Acessing a full row
print(f"Second row:\n{a[1]}")
[[0 0 0]
 [0 1 0]
 [0 0 2]]

Second row, second column: 1

[[ 0  0  0]
 [ 0  1  0]
 [ 0 10  2]]

Second row:
[0 1 0]

Slicing is just a way to access multiple array items at once:

a = np.arange(10)
print(a, end="\n\n")

print("1st:", a[2:9])
print("2nd:", a[2:])
print("3rd:", a[:5])
print("4th:", a[2:9:3])  # [start:end:step]
print("5th:", a[a > 5])  # using a mask
[0 1 2 3 4 5 6 7 8 9]

1st: [2 3 4 5 6 7 8]
2nd: [2 3 4 5 6 7 8 9]
3rd: [0 1 2 3 4]
4th: [2 5 8]
5th: [6 7 8 9]

Get further info on NumPy arrays here!