For the examples in this section we will assume that the numpy module has been installed,
given that it is not a standard part of Python, and that when not explicitly stated it is
NumPy has its own version of multi-dimensional arrays, called the N-dimensional array,
which allows efficient manipulation. A basic Python multi-dimensional list can be
The elements in a NumPy array can be accessed in the same way that ordinary Python
matrices (like lists of lists) are accessed, although there is an alternative syntax that is
NumPy will determine the data type of matrices from the data types of its elements. For
example, the array x above will be of type int because its contents are integers. If instead
you wanted x to be floating point you could either make one of the numbers explicitly
Note that NumPy has its own data types, so you can be even more specific about which
kind of number you require, beyond the regular Python types. Here we specify 32-bit
These special types are usually not needed in regular Python, but can be very handy
when interfacing array data with C code (see
Chapter 27
).
The shape of a NumPy array (i.e. number of rows, columns) is determined via:
x.shape # (2, 3)
and its total size via:
x.size # 6 (= 2 x 3)
What NumPy calls the dimension of an array is the same as the length of the shape:
x.ndim # 2
len(x.shape) # 2
There are various ways of making arrays of a standard kind, without having to convert
other Python data structures. For example, we can create arrays of specified size
consisting of all zeros, all ones or an identity matrix (zeros but ones on the diagonal):
x = numpy.zeros((2,3)) # 2 x 3 matrix full of 0.0
x = numpy.ones((3,2)) # 3 x 2 matrix full of 1.0
x = numpy.identity(3) # 3 x 3 identity; floating point
x = numpy.identity(3, numpy.int) # 3 x 3 identity; integer
The regular arithmetic operations work on NumPy arrays, and operate in an element-
by-element manner:
x = numpy.array([1.0, 2.0, 3.0])
y = numpy.array([3.0, 4.0, 5.0])
x + y # array([4.0, 6.0, 8.0]) i.e. 1+3, 2+4, 3+5
x * y # array([3.0, 8.0, 15.0])
x – y # array([-2.0, -2.0, -2.0])
x / y # array([0.33333333, 0.5, 0.6])
Also, arithmetic can involve single numbers, whereupon all elements of the array are
operated on with that number:
x + 1.0 # array([2.0, 3.0, 4.0])
y * 5.0 # array([15.0, 20.0, 25.0])
To perform other mathematical operations on arrays, NumPy has the array equivalent of
most of the functions found in the math module and these work efficiently to perform the
operation for each element of the array. As well as NumPy arrays the functions will accept
regular Python lists or tuples as input, but an array is returned:
angles = numpy.array([30.0, 60.0, 90.0, 135.0])
radians = numpy.radians(angles)
cosines = numpy.cos(radians) # array([0.866, 0.50, 0.0, -0.707])
numpy.log([10.0, 2.71828, 1.0]) # array([2.302585, 1.0, 0.0])
numpy.exp([2.302585, 1.0, 0.0]) # array([10.0, 2.71828, 1.0])
Do'stlaringiz bilan baham: