The original tutorial may be found at this SciPy Tentative NumPy Tutorials.
One thing I notice is that the original tutorial uses heavily syntax like:
from numpy import *
which according to the PEP8 Style Guide should be avoided.
The PEP8 Style Guide recommends to use syntax like this instead as good practice:
import numpy as np
I use this IPython Notebook is to re-write the examples using the PEP8 Import Syntax.
import numpy as np
Original Tutorial here
Create an array of 15 integers ranging between 0 to 14, to a matrix (a NumPy array) of 3 rows by 5 columns. Assign this to a
.
a = np.arange(15).reshape(3, 5)
a
What is the matrix shape in rows (1st dimension) and columns (2nd dimension)?
a.shape
What is the number of dimensions? (should expect 2: one for rows, and one for columns).
a.ndim
What is the name of the data type? (should expect some form of integer type).
a.dtype.name
Note that the data type is of type int32
. i.e. 32-bit integer. i.e. 4 (=32/8) byte integer.
The itemsize
method tells us that each element in the numpy array is of size 4 bytes each.
a.itemsize
How many elements are there in the NumPy array?
a.size
Just to confirm that a
is a numpy array...
type(a)
Create a new array and assign to b
.
b = np.array([6, 7, 8])
b
Just to confirm that b
is a numpy array...
type(b)
Original Tutorials here
There are several ways to create arrays.
For example, you can create an array from a regular Python list or tuple using the array function. The type of the resulting array is deduced from the type of the elements in the sequences.
a = np.array([2, 3, 4])
a
a.dtype
b = np.array([1.2, 3.5, 5.1])
b
b.dtype
A frequent error consists in calling array with multiple numeric arguments, rather than providing a single list of numbers as an argument.
# a = np.array(1, 2, 3, 4) # WRONG
a = np.array([1, 2, 3, 4]) # RIGHT
a
array
transforms sequences of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on.
b = np.array([(1.5, 2, 3), (4, 5, 6)])
b
The type of the array can also be explicitly specified at creation time:
c = np.array([[1, 2], [3, 4]], dtype=complex)
c
Create a 3 (rows) by 4 (columns) NumPy array filled with zeros.
np.zeros((3, 4))
Create a 3 (rows) by 4 (columns) NumPy array filled with ones.
np.ones((3, 4))
Create a 2 (outter-most) by 3 by 4 (inner-most) NumPy array filled with ones. Set element data type to int16
.
np.ones((2, 3, 4), dtype=np.int16)
Create a 2 by 3 empty NumPy Array.
np.empty((2,3))
Original Tutorials here
When you print an array, NumPy displays it in a similar way to nested lists, but with the following layout:
One-dimensional arrays are then printed as rows, bidimensionals as matrices and tridimensionals as lists of matrices.
Create a 1D array.
a = np.arange(6)
print a
Create a 2D array.
b = np.arange(12).reshape(4, 3)
print b
Create a 3D array.
c = np.arange(24).reshape(2, 3, 4)
print c
Create a 4D array.
d = np.arange(120).reshape(2, 3, 4, 5)
print d
If an array is too large to be printed, NumPy automatically skips the central part of the array and only prints the corners.
What is the current print option? (note the threshold input)
np.get_printoptions()
Let's try to print something.
print np.arange(10000)
print np.arange(10000).reshape(100,100)
To disable this behaviour and force NumPy to print the entire array, you can change the printing options using set_printoptions.
np.set_printoptions(threshold='nan')
print np.arange(10000)
Depending on where you view the content, the above output may be framed (In IPython Notebook, this would be a small window where you get to scroll up and down), or display-all (In GitHub, it reders the entire output).
Let's view current print options and reset to previous stage.
np.get_printoptions()
np.set_printoptions(threshold=1000)
np.get_printoptions()
Let's try it out!
print np.arange(10000)
Original Tutorials here
Arithmetic operators on arrays apply elementwise. A new array is created and filled with the result.
a = np.array([20, 30, 40, 50])
a
b = np.arange(4)
b
c = a - b
c
b**2
10*np.sin(a)
a < 35
Unlike in many matrix languages, the product operator *
operates elementwise in NumPy arrays. The matrix product can be performed using the dot
function or creating matrix objects (see matrix section of this tutorial).
matrixA = np.array([[1, 1],
[0, 1]])
matrixB = np.array([[2, 0],
[3, 4]])
Elementwise product:
matrixA * matrixB
Matrix product:
np.dot(matrixA, matrixB)
Some operations, such as +=
and *=
, act in place to modify an existing array rather than create a new one.
a = np.ones((2, 3), dtype=np.int)
a
a.dtype.name
b = np.random.random((2, 3))
b
b.dtype.name
a *= 3
a
Add b
(float64 type) to a
( int32 type). To make this possible, during the computation phase, b
is lowered temporarily to in32 type, add to a
. The eventual b
type is unchanged.
a += b
a
a.dtype.name
b.dtype.name
Let's try the other way round.
b += a
b.dtype.name
a.dtype.name
Note that the type of a
and b
are unchanged.
When operating with arrays of different types, the type of the resulting array corresponds to the more general or precise one (a behavior known as upcasting).
a = np.ones(3, dtype=np.int32)
a
b = np.linspace(0, np.pi, 3)
b
a.dtype.name
b.dtype.name
c = a + b
c
c.dtype.name
c
d = np.exp(c*1j)
c*1j
d
d.dtype.name
Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray
class.
a = np.random.random((2,3))
a
a.sum()
a.min()
a.max()
By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:
b = np.arange(12).reshape(3,4)
b
Compute sum of each column (the inner nest is axis 0):
b.sum(axis=0)
Compute sum of each row (the next outer nest):
b.sum(axis=1)
Compute min of each row
b.min(axis=1)
Compute cummulative sum along each row:
b.cumsum(axis=1)
Original Tutorials here
NumPy provides familiar mathematical functions such as sin
, cos
, and exp
. In NumPy, these are called "universal functions"(ufunc
). Within NumPy, these functions operate elementwise on an array, producing an array as output.
See the NumPy Example List for a more comprehensive list of NumPy Universal Functions.
b = np.arange(3)
b
np.exp(b)
np.sqrt(b)
c = np.array((2., -1., 4.))
c
np.add(b, c)
Original Tutorials here
One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python sequences.
a = np.arange(10.)**3
a
Grab element at position 2:
a[2]
Grab elements within the asymetric range [2:5]
(include elements at position 2, 3, 4 ; exclude 5)
a[2:5]
Grab elements within the asymetric range [:6]
with step 2
(Include elements at position 0, 2, 4; exclude anything from 6 upwards.)
a[:6:2]
Let's replace some individual elements with new values:
a[:6:2] = -1000 # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
a
Reverse a
. This blog post might come in handy.
a[::-1]
Let's print the cube root (i.e. power of 1/3
) of each element in the NumPy array. the root of any
a
for i in a:
print i**(1/3.)
When using fractional power against a negative base number...
Note: I am not quite sure why it does not compute the cube root of -1000., which should work out to be -0.999 ish. i.e. Cube root of -1000
seems to work in the basic case, like this:
-10.**3.
-1000**(1/3.)
This does not seem to work against a NumPy array element. Strange?
a = np.array([-1000.])
a
a[0]
a[0]**(1/3.)
Likewise in a for loop, no luck neither.
for i in a:
print i**(1/3.)
Have just found the solution from this forum post. It looks like for fractional power, some special treatment may be required.
x = np.array([-81,25])
x
xRoot5 = np.sign(x) * np.absolute(x)**(1.0/5.0)
xRoot5
xRoot5**5
There is also an alternative solution using the math
module, obtained from this StackOverflow post.
import math
def myPower(base, power):
if base > 0:
return math.pow(base, float(power))
elif base < 0:
return -math.pow(abs(base), float(power))
else:
return 0
myPower(-3, (1./3.))
Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by commas:
def f(x,y):
return 10*x + y
f
Use the NumPy fromfunction to construct an array.
b = np.fromfunction(f, (5, 4), dtype=np.int)
b
We index an element from outer to inner nest.
b[2,3]
b[0:5, 1]
b[:,1]
b[1:3,:]
When fewer indices are provided than the number of axes, the missing indices are considered complete slices:
the last row. Equivalent to b[-1,:]
b[-1]
The expression within brackets in b[i] is treated as an i followed by as many instances of : as needed to represent the remaining axes. NumPy also allows you to write this using dots as b[i,...]
.
The dots(...) represent as many colons as needed to produce a complete indexing tuple. For example, if x is a rank 5 array (i.e., it has 5 axes), then
x[1,2,...]
is equivalent to x[1,2,:,:,:]
,x[...,3]
to x[:,:,:,:,3]
andx[4,...,5,:]
to x[4,:,:,5,:]
c = np.array([[[ 0, 1, 2],
[10, 12, 13]],
[[100, 101, 102],
[110, 112, 113]]])
c
c.shape
c[1,...]
c[1]
c[1,:,:]
c[...,2]
c[:,:,2]
Iterating over multidimensional arrays is done with respect to the first axis:
b
for row in b:
print row
However, if one wants to perform an operation on each element in the array, one can use the flat
attribute which is an iterator over all the elements of the array (from inner nest to outer):
for element in b.flat:
print element
We have now completed the Tentative NumPy Tutorials: Lesson 2 - Basics.