@KarlYan95
2017-07-24T15:11:24.000000Z
字数 1930
阅读 740
Python
Generate a 10 x 3 array of random numbers (in range [0,1]). For each row, pick the number closest to 0.5.
abs and argsort to find the column j closest for each row.a[i,j] – the array i must contain the row numbers corresponding to stuff in j.)
import numpy as npa = np.random.random(size=(10, 3)) # generate a 10*3 arrayb = (a - 0.5).__abs__().argsort() # minus 0.5, get the absolute value and the indices that sort the arrayc = (b[:, :] == 0) # get bool masks, if b[i,j]==0 then c[i,j]==Trueextract_a = a[c] # using masks to pick the number closest to 0.5print extract_a
Computes and print, based on the data in populations.txt... The mean
and std of the populations of each species for the years in the
period.
1. Which year each species had the largest population.
2. Which species has the largest population for each year. (Hint: argsort & fancy indexing of np.array(['H', 'L', 'C']))
3. Which years any
of the populations is above 50000. (Hint: comparisons and np.any)
4. The top 2 years for each species when they had the lowest populations.
(Hint: argsort, fancy indexing)
5. Compare (plot) the change in hare population (see help(np.gradient)) and the number of lynxes. Check correlation (see help(np.corrcoef)).
... all without for-loops.
import numpy as npdata = np.loadtxt('data/populations.txt')year, hares, lynxes, carrots = data.Tpopulations = data[:,1:]print " Hares, Lynxes, Carrots"print "Mean:", populations.mean(axis=0)print "Std:", populations.std(axis=0)j_max_years = np.argmax(populations, axis=0)print "Max. year:", year[j_max_years]max_species = np.argmax(populations, axis=1)species = np.array(['Hare', 'Lynx', 'Carrot'])print "Max species:"print yearprint species[max_species]above_50000 = np.any(populations > 50000, axis=1)print "Any above 50000:", year[above_50000]j_top_2 = np.argsort(populations, axis=0)[:2]print "Top 2 years with lowest populations for each:"print year[j_top_2]hare_grad = np.gradient(hares, 1.0)print "diff(Hares) vs. Lynxes correlation", np.corrcoef(hare_grad, lynxes)[0,1]import matplotlib.pyplot as pltplt.plot(year, hare_grad, year, -lynxes)plt.savefig('plot.png')