Numpy and Scipy Howto

Numpy and Scipy Howto

Stuff I’ve found useful for numpy/scipy (and matplotlib):

Ways of Storing and Accessing Data

recarray

numpy.recarray: Construct an ndarray that allows field access using attributes.

Arrays may have a data-types containing fields, analagous to columns in a spread sheet. An example is [(x, int), (y, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['x'] and arr['y']. Record arrays allow the fields to be accessed as members of the array, using arr.x and arr.y.

>>> from numpy import *
>>> num = 2
>>> a = recarray(num, formats='i4,f8,f8',names='id,x,y')
>>> a['id'] = [3,4]
>>> a['id']
array([3, 4])
>>> a = rec.fromrecords([(35,1.2,7.3),(85,9.3,3.2)], names='id,x,y')       # fromrecords is in the numpy.rec submodule
>>> a['id']
array([35, 85])

Computing A Histogram and Kernel


import scipy as S
import scipy.stats as stats
from matplotlib import pyplot
nns, bins, patches = pyplot.hist(values, bins=120)

kernel = scipy.stats.kde.gaussian_kde(values)

get kernel to match histogram (historgram is not normalized)

scaler = nns[0] / kernel(bins[0]) * (bins[1] - bins[0]) pyplot.plot(bins, map(lambda x: scaler*kernel(x), bins), 'k-')

Compute a 3D Spectogram from a WAV File

See this script: http://rufuspollock.org/code/misc/spectrogram3d.py

HDF5, PYTables and h5py

Leave a Reply