NumPy, SciPy and SciKits

From AstroEdWiki
Revision as of 21:48, 20 February 2013 by WikiSysop (talk | contribs) (→‎NumPy)
Jump to navigation Jump to search

Python provides a framework on which numerical and scientific data processing can be built. As part of our short course on Python for Physics and Astronomy we will look at the capabilities of the NumPy, SciPy and SciKits packages. This is a brief overview with a few examples drawn primarily from the excellent but short introductory book SciPy and NumPy by Eli Bressert (O'Reilly 2012).

NumPy

NumPy adds arrays and linear albegra to Python, with special functions, transformations, the ability to operate on all elements of an array in one stroke.

Arrays are at the heart of NumPy. The program

import numpy as np

# Use arange to create an array of 100 elements
myarray = np.arange(1e2)
print myarray

produces an array of 100 values:

array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,
       11.,  12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,
       22.,  23.,  24.,  25.,  26.,  27.,  28.,  29.,  30.,  31.,  32.,
       33.,  34.,  35.,  36.,  37.,  38.,  39.,  40.,  41.,  42.,  43.,
       44.,  45.,  46.,  47.,  48.,  49.,  50.,  51.,  52.,  53.,  54.,
       55.,  56.,  57.,  58.,  59.,  60.,  61.,  62.,  63.,  64.,  65.,
       66.,  67.,  68.,  69.,  70.,  71.,  72.,  73.,  74.,  75.,  76.,
       77.,  78.,  79.,  80.,  81.,  82.,  83.,  84.,  85.,  86.,  87.,
       88.,  89.,  90.,  91.,  92.,  93.,  94.,  95.,  96.,  97.,  98.,
       99.])


Arrays can be shaped with reshape(i,j,k,...)

mynewarray = myarray.reshape(20,5)
print mynewarray
array([[  0.,   1.,   2.,   3.,   4.],
      [  5.,   6.,   7.,   8.,   9.],
      [ 10.,  11.,  12.,  13.,  14.],
      [ 15.,  16.,  17.,  18.,  19.],
      [ 20.,  21.,  22.,  23.,  24.],
      [ 25.,  26.,  27.,  28.,  29.],
      [ 30.,  31.,  32.,  33.,  34.],
      [ 35.,  36.,  37.,  38.,  39.],
      [ 40.,  41.,  42.,  43.,  44.],
      [ 45.,  46.,  47.,  48.,  49.],
      [ 50.,  51.,  52.,  53.,  54.],
      [ 55.,  56.,  57.,  58.,  59.],
      [ 60.,  61.,  62.,  63.,  64.],
      [ 65.,  66.,  67.,  68.,  69.],
      [ 70.,  71.,  72.,  73.,  74.],
      [ 75.,  76.,  77.,  78.,  79.],
      [ 80.,  81.,  82.,  83.,  84.],
      [ 85.,  86.,  87.,  88.,  89.],
      [ 90.,  91.,  92.,  93.,  94.],
      [ 95.,  96.,  97.,  98.,  99.]])


Notice that reshape says in effect to make the linear array into one with 20 elements, each of 5 elements. When printed, this example looks like 20 rows, each with 5 columns.

You can also make arrays from a list

myarray = np.array( [1,3,5,7,11,13] )

and the array can be turned back into a list

mylist = myarray.tolist()
print mylist
[1, 3, 5, 7, 11, 13]