My first brush with NumPy happened over writing a block of code to make a plot using pylab. ⇣
pylabis part of
matplotlib.pylab) and tries to give you a MatLab like environment.
matplotlibhas a number of dependencies, among them
numpywhich it imports under the common alias
scipyis not a dependency of
Given below, are 2 sets of code that do the same thing; one without NumPy and the other with NumPy. They output the following graph using PyLab:
Code without NumPy
Code with NumPy
The difference in code lies in how the variable
diffTemps is calculated.
diffTemps = list(np.array(highTemps) - np.array(lowTemps))
seems more readable than
diffTemps = [highTemps[i] - lowTemps[i] for i in range(len(lowTemps))]
Notice how straight forward it is with NumPy. At the core of the NumPy package, is the ndarray object. This encapsulates n-dimensional arrays of homogeneous data types, with many operations being performed in compiled code for performance. element-by-element operations are the “default mode” when an ndarray is involved, but the element-by-element operation is speedily executed by pre-compiled C code.