Points d’implémentation avec numpy#
Links: notebook
, html, PDF
, python
, slides, GitHub
Quelques écritures efficaces et non efficaces avec numpy.
from jyquickhelper import add_notebook_menu
add_notebook_menu()
accéder à un élément en particulier#
import numpy
mat = numpy.zeros((5, 5))
for i in range(mat.shape[0]):
for j in range(mat.shape[1]):
mat[i, j] = i * 10 + j
mat
array([[ 0., 1., 2., 3., 4.],
[10., 11., 12., 13., 14.],
[20., 21., 22., 23., 24.],
[30., 31., 32., 33., 34.],
[40., 41., 42., 43., 44.]])
mat[2, 3], mat[2][3]
(23.0, 23.0)
%timeit mat[2, 3]
116 ns ± 4.49 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit mat[2][3]
319 ns ± 57 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Les deux écritures ont l’air identique puisqu’elle retourne le même
résultat. Néanmoins, mat[2][3]
crée un tableau temporaire puis
extrait un élément. Les éléments ne sont pas recopiés mais un objet
intermédiaire est créé.
mat[2]
array([20., 21., 22., 23., 24.])