Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

advanced array manipulations right out of the box.


There are several different ways to create arrays in NumPy. One way is to create an array from an
existing Python list or tuple, as in this example:


Click here to view code image


>>> import numpy
>>> a = numpy.array(([1, 2, 3], [0, 2, 4], [3, 2, 1]))
>>> print(a)
[[1 2 3]
[0 2 4]
[3 2 1]]
>>>

This example creates a 3-by-3 array using three Python lists.


If you don’t define a data type, Python assumes the data type for the data. If you need to change the
data type of the array values, you can specify it as a second parameter to the array() function. For
example, the following example causes the values to be stored in the floating-point data type:


Click here to view code image


>>> a = numpy.array(([1,2,3], [4,5,6]), dtype="float")
>>> print(a)
[[ 1. 2. 3.]
[ 4. 5. 6.]]
>>>

You can also generate default arrays of either all zeros or all ones, like this:


>>> x = numpy.zeros((3,5))
>>> print(x)
[[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]]
>>> y = numpy.ones((5,2))
>>> print(y)
[[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]]
>>>

You can also create an array of regularly incrementing values by using the arrange() function, as
shown here:


>>> c = numpy.arange(10)
>>> print(c)
[0 1 2 3 4 5 6 7 8 9]
>>>

You can also specify the starting and ending values, as well as the increment value.


Using NumPy Arrays


The beauty of NumPy lies in its ability to handle array math. These functions are somewhat of a pain
using standard Python lists or tuples, as you have to manually loop through the list or tuple to add or
multiply the individual array values. With NumPy, it’s just a simple calculation, as shown here:

Free download pdf