← retour aux snippets

numpy: création arrays (ones/zeros/arange)

Créer des arrays avec tailles/dtypes contrôlés.

python numpy #numpy#array#creation

objectif

Créer des arrays avec tailles/dtypes contrôlés.

code minimal

import numpy as np

a = np.zeros((2,3), dtype=np.float32)
b = np.ones(4, dtype=int)
c = np.arange(0, 5, 2)
print(a.shape, b.shape, c.tolist())

utilisation

import numpy as np

m = np.full((2,2), 7)
print(m.tolist())

variante(s) utile(s)

import numpy as np

r = np.linspace(0.0, 1.0, num=5, dtype=np.float64)
print(r.tolist())

notes

  • Préférez les dtypes explicites pour reproductibilité.