Description

Here are a bunch of samples used to demonstrate various features of numpy. See also the numpy talk: November2010Notes

I recommend that you fire up the command line, or better yet iPython, and copy and paste these in line my line into the interpreter.

code

start.py

A couple things that the other scripts use

   1 #!/usr/bin/env python
   2 """
   3 script to start up demo for numpy talk
   4 """
   5 
   6 import numpy as np
   7 import sys
   8 
   9 def print_info(a):
  10     print "a:"
  11     print a
  12     print "a.shape:", a.shape
  13     print "a.dtype:", a.dtype
  14     print "a.itemsize", a.itemsize
  15     print "a.ndim:", a.ndim
  16     print "a.strides", a.strides
  17     print "a.flags:\n", a.flags
  18     

constructors.py

Various ways to build a numpy array

   1 # data types
   2 from start import *
   3 
   4 # from scratch:
   5 print np.ones((3,)) # default dtype is float64
   6 
   7 print np.zeros((2,3), dtype=np.int32)
   8 
   9 print np.empty((3,3), dtype=np.float32) # not initialized!
  10 
  11 # for a range:
  12 # integers:
  13 print np.arange(10)
  14 
  15 # for floats
  16 print np.linspace(0, 1, 11)
  17 
  18 print np.logspace(0, 3, 4)
  19 
  20 
  21 # from existing data:
  22  
  23 print np.array([(1, 2),
  24                 (3, 4.0),
  25                 (5, 6)]) # auto-determined dtype
  26 
  27 # maybe an array?
  28 a = np.arange(5)
  29 b = np.asarray(a)
  30 print a is b
  31 
  32 #or not:
  33 a = range(5)
  34 b = np.asarray(a)
  35 print a is b
  36 
  37 print np.ascontiguousarray(a)# forces contiguous data block
  38 
  39 # from binary data:
  40 s = 'abcdefg'
  41 a = np.frombuffer(s, dtype=np.uint8)
  42 print a
  43 
  44 print np.fromstring('\x12\x04', dtype=np.uint8) # really should be bytes...
  45 
  46 # from (and to) binary file:
  47 a = np.arange(5, dtype=np.float32) # jsut a binary dump!
  48 
  49 a.tofile('junk.dat')
  50 
  51 print np.fromfile('junk.dat', dtype=np.float32) # need dtype!

basic.py

Basic array reshaping, etc. operations.

   1 from start import *
   2 
   3 # reshaping:
   4 
   5 a = np.arange(12)
   6 
   7 print a.shape
   8 a.shape = (3,4)
   9 print a
  10 
  11 print np.reshape(a, (2,6) )
  12 
  13 # unknown dimension
  14 a.shape = ( -1, 2)
  15 print a
  16 
  17 # flatten
  18 for i in a.flat: # iterator
  19     print i # iterator
  20 
  21 print np.ravel(a)
  22 
  23 print a.T
  24 
  25 print 
  26 
  27 # checking dimensions:
  28 a = np.ravel(a)
  29 
  30 print np.atleast_2d(a)
  31 
  32 # reducing:
  33 a.shape = (2,1,6)
  34 b = np.squeeze(a)
  35 print b.shape
  36 
  37 # re-arranging:
  38 print b
  39 print np.flipud(b)
  40 print np.fliplr(b)

slice.py

Very simple slicing

   1 from start import *
   2 
   3 # create an array:
   4 a = np.arange(12)
   5 print_info(a)
   6 
   7 # A slice is a view:
   8 b = a[3:6]
   9 print b
  10 
  11 b[0] = 44
  12 
  13 print b
  14 print a

dtypes.py

Experiments with custom dtypes

   1 from start import *
   2 
   3 # a custom dtype:
   4 dt = np.dtype([('first_name', np.str_, 16),
   5                ('last_name',  np.str_, 24),
   6                ('grades',     np.float64, (2,)),
   7                ])
   8 
   9 # create an array of this type:
  10 
  11 a = np.empty((3,), dtype=dt)
  12 
  13 #Fill it up:
  14  
  15 a[0] = ('Fred', 'Jones', (92.3, 86.2))    
  16 a[1] = ('Bob', 'Smith', (85.1, 88.4))    
  17 a[2] = ('George', 'Roberts', (76.3, 91.5))    
  18 
  19 print_info(a)
  20 
  21 # extract a field:
  22 
  23 print a['first_name']
  24 
  25 # do some math on a field:
  26 
  27 grades = a['grades']
  28 print grades
  29 
  30 # do some math:
  31 print grades.mean()
  32 
  33 # still a view on the data
  34 
  35 print_info(grades) # note the strides!

structure.py

A bit about how arrays are internally structured

   1 from start import *
   2 
   3 # create an array:
   4 a = np.arange(12)
   5 print_info(a)
   6 
   7 # reshape it
   8 a.shape = (3,4)
   9 print_info(a)
  10 
  11 # transpose it
  12 
  13 b = a.transpose()
  14 print_info(b) 
  15 
  16 # reshape again
  17 a.shape = (2,2,3)
  18 print_info(a)
  19 
  20 # take a slice:
  21 s = a[:,1,:]
  22 print_info(s)

broadcasting.py

Intro to broadcasting

   1 from start import *
   2 
   3 a = np.ones((3,4))
   4 
   5 print a * 3
   6 
   7 x = np.linspace(0,10,4)
   8 y = np.linspace(100,200,3)
   9 
  10 x.shape = (1, -1)
  11 y.shape = (-1, 1)
  12 
  13 print x
  14 print y
  15 
  16 print a * x
  17 print a * y
  18 
  19 print np.sqrt(x**2 * y**2)

memory.py

How much memeory does a numpy array vs. list take?

   1 from start import *
   2 
   3 print "size of empty list:"
   4 print sys.getsizeof([])
   5 
   6 print "size of empty ndarray:"
   7 print sys.getsizeof(np.array([]))
   8 
   9 print "size of python float:"
  10 print sys.getsizeof(1.0)
  11 
  12 print "size of numpy float64:"
  13 print np.array(1.0).itemsize
  14 
  15 print "A 1000 element list of floats:"
  16 print 36 + 1000*32 + 1000*16, 'bytes'
  17 
  18 print "A 1000 element list of floats:"
  19 print 40 + 1000*8, 'bytes'

objects.py

A demo of using arrays of python objects

   1 # Object arrays:
   2 from start import *
   3 
   4 # create an empty array:
   5 
   6 a = np.empty((2,3), dtype=np.object)
   7 
   8 print a
   9 
  10 # put stuff into it:
  11 
  12 a[0,0] = "a string"
  13 a[0,1] = 4.5
  14 a[0,2] = (1,2,3)
  15 a[1,:] = [6, {'a':3}, 3.4]
  16 
  17 print a
  18 
  19 # a row:
  20 print a[1,:]
  21 
  22 # a column:
  23 print a[:,1]
  24 
  25 # an item (a dict in this case)
  26 print a[1,1]
  27 print a[1,1]['a']

NumpyExamples (last edited 2010-12-07 20:37:52 by 161)