How to create (extract) a sample from an array in python ?

Published: March 08, 2019

DMCA.com Protection Status

Let's consider a table called "a", goal: extract a random sample of size 3 from the table

import numpy as np

a  = 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)

returns

[[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]]

Stap 1: shuffle

print('Step 1: shuffle a')

np.random.shuffle(a)

print(a)

returns

[[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]]

Stap 2: slice

print('Step 2: slice')

s = a[:3,:]

print(s)

returns

[[6 2 9 7 4]
 [8 9 4 9 6]
 [5 1 8 1 7]]

Example of application

Create a random sample from a data file and plot the points of a map:

How to plot scatter points from a random sample on a global map using matplotlib and basemap ?
How to plot scatter points from a random sample on a global map using matplotlib and basemap ?

#!/usr/bin/env python

from mpl_toolkits.basemap import Basemap, cm

from scipy import stats, mgrid, c_, reshape, random, rot90
from pylab import *
from mpl_toolkits.axes_grid1 import make_axes_locatable

import numpy as np
import seaborn as sn
import pandas as pd

import matplotlib as mpl

mpl.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 Observations

fig = 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()

References

Links Site
shuffle docs.scipy
Image

of