Exemple de comment créer (extraire) un échantillon à partir d'un tableau en python ?
Soit un tableau 2D appelé "a", on veut extraire un échantillon aléatoire du tableau composé par exemple de 3 éléments:
Table des matières
import numpy as npa = np.array([[0, 4, 9, 8, 2],[1, 5, 4, 1, 7],[2, 5, 1, 9, 3],[3, 7, 5, 9, 7],[4, 2, 6, 6, 3],[5, 1, 8, 1, 7],[6, 2, 9, 7, 4],[7, 9, 2, 9, 3],[8, 9, 4, 9, 6],[9, 6, 2, 7, 2]])print(a)
donne
[[0 4 9 8 2][1 5 4 1 7][2 5 1 9 3][3 7 5 9 7][4 2 6 6 3][5 1 8 1 7][6 2 9 7 4][7 9 2 9 3][8 9 4 9 6][9 6 2 7 2]]
étape 1: shuffle
print('Step 1: shuffle a')np.random.shuffle(a)print(a)
donne
[[6 2 9 7 4][8 9 4 9 6][5 1 8 1 7][7 9 2 9 3][0 4 9 8 2][3 7 5 9 7][4 2 6 6 3][2 5 1 9 3][1 5 4 1 7][9 6 2 7 2]]
étape 2: slice
print('Step 2: slice')s = a[:3,:]print(s)
donne
[[6 2 9 7 4][8 9 4 9 6][5 1 8 1 7]]
Exemple d'application
Extraire un échantillon d'un fichier de données et tracer les points sur une carte globale:

#!/usr/bin/env pythonfrom mpl_toolkits.basemap import Basemap, cmfrom scipy import stats, mgrid, c_, reshape, random, rot90from pylab import *from mpl_toolkits.axes_grid1 import make_axes_locatableimport numpy as npimport seaborn as snimport pandas as pdimport matplotlib as mplmpl.style.use('seaborn')data = np.loadtxt('/Users/bmarcha1/Desktop/media/files/monthly_modis_cldclass_lidar/2008_01_sample_00_modis_caliop_cldclass_lidar.txt', skiprows=1)np.random.shuffle(data)data = data[:10000,:]#---------------------------------------------------------------------------------------## Scatter Plots Observationsfig = plt.figure()ax = fig.add_subplot(111)m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90, llcrnrlon=-180,urcrnrlon=180,resolution='c')m.drawcoastlines()m.drawparallels(np.arange(-90.,90.,30.))m.drawmeridians(np.arange(-180.,180.,30.))m.scatter(data[:,1],data[:,0],s=2)plt.title('Random sample with a reservoir for January 2008',fontsize='10')plt.xlim(-180,180)plt.ylim(-90,90)plt.xlabel('Longitude',fontsize='8')plt.ylabel('Latitude',fontsize='8')filename ='random_sample_global_map.png'plt.savefig(filename, dpi=200, bbox_inches='tight' )plt.show()#plt.close()
Références
| Liens | Site |
|---|---|
| shuffle | docs.scipy |
