Seléctionner aléatoirement un élément d'une matrice (tableau) avec python et numpy

Active 07 décembre 2016    /    Viewed 2277    /    Comments 0    /    Edit


Exemple sur comment seléctionner aléatoirement un élément d'une matrice 2d avec python:

\begin{equation}
A = \left( \begin{array}{ccc}
1 & 2 \\
4 & 5 \\
7 & 8
\end{array}\right)
\end{equation}

>>> import numpy as np
>>> from random import randint
>>> M = np.array([[1,2],[4,5],[7,8]])
>>> M
array([[1, 2],
       [4, 5],
       [7, 8]])
>>> M_shape = M.shape
>>> M_shape 
(3, 2)
>>> i = randint(0,M_shape[0]-1)
>>> j = randint(0,M_shape[1]-1)
>>> i,j
(1, 0)
>>> M[i,j]
4

Recherches associées

Liens Site
Select cells randomly from NumPy array - without replacement stackoverflow
Generate random integers between 0 and 9 stackoverflow
random — Generate pseudo-random numbers python doc


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!