[关闭]
@KarlYan95 2017-07-24T15:11:24.000000Z 字数 1930 阅读 689

Python 练习

Python


1. Array manipulations

Generate a 10 x 3 array of random numbers (in range [0,1]). For each row, pick the number closest to 0.5.

  1. import numpy as np
  2. a = np.random.random(size=(10, 3)) # generate a 10*3 array
  3. b = (a - 0.5).__abs__().argsort() # minus 0.5, get the absolute value and the indices that sort the array
  4. c = (b[:, :] == 0) # get bool masks, if b[i,j]==0 then c[i,j]==True
  5. extract_a = a[c] # using masks to pick the number closest to 0.5
  6. print extract_a

2. Data statistics

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.

  1. import numpy as np
  2. data = np.loadtxt('data/populations.txt')
  3. year, hares, lynxes, carrots = data.T
  4. populations = data[:,1:]
  5. print " Hares, Lynxes, Carrots"
  6. print "Mean:", populations.mean(axis=0)
  7. print "Std:", populations.std(axis=0)
  8. j_max_years = np.argmax(populations, axis=0)
  9. print "Max. year:", year[j_max_years]
  10. max_species = np.argmax(populations, axis=1)
  11. species = np.array(['Hare', 'Lynx', 'Carrot'])
  12. print "Max species:"
  13. print year
  14. print species[max_species]
  15. above_50000 = np.any(populations > 50000, axis=1)
  16. print "Any above 50000:", year[above_50000]
  17. j_top_2 = np.argsort(populations, axis=0)[:2]
  18. print "Top 2 years with lowest populations for each:"
  19. print year[j_top_2]
  20. hare_grad = np.gradient(hares, 1.0)
  21. print "diff(Hares) vs. Lynxes correlation", np.corrcoef(hare_grad, lynxes)[0,1]
  22. import matplotlib.pyplot as plt
  23. plt.plot(year, hare_grad, year, -lynxes)
  24. plt.savefig('plot.png')
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注