官术网_书友最值得收藏!

Learning NumPy

So, let's import NumPy and play with it a bit. For that, we need to start the Python interactive shell:

>>> import numpy
>>> numpy.version.full_version
1.13.3

As we do not want to pollute our namespace, we certainly should not use the following code:

>>> from numpy import *

If we do this, then, for instance, numpy.array will potentially shadow the array package that is included in standard Python. Instead, we will use the following convenient shortcut:

>>> import numpy as np
>>> a = np.array([0,1,2,3,4,5])
>>> a
array([0, 1, 2, 3, 4, 5])
>>> a.ndim
1
>>> a.shape
(6,)

With the previous code snippet, we created an array in the same way that we would create a list in Python. However, the NumPy arrays have additional information about the shape. In this case, it is a one-dimensional array of six elements. That's no surprise so far.

We can now transform this array into a two-dimensional matrix:

>>> b = a.reshape((3,2))
>>> b
array([[0, 1],
[2, 3],
[4, 5]])
>>> b.ndim
2
>>> b.shape
(3, 2)

It is important to realize just how much the NumPy package is optimized. For example, doing the following avoids copies wherever possible:

>>> b[1][0] = 77
>>> b
array([[ 0, 1],
[77, 3],
[ 4, 5]])
>>> a
array([ 0, 1, 77, 3, 4, 5])

In this case, we have modified the value 2 to 77 in b, and we immediately see the same change reflected in a, as well. Keep in mind that whenever you need a true copy, you can always perform the following:

>>> c = a.reshape((3,2)).copy()
>>> c
array([[ 0, 1],
[77, 3],
[ 4, 5]])
>>> c[0][0] = -99
>>> a
array([ 0, 1, 77, 3, 4, 5])
>>> c
array([[-99, 1],
[ 77, 3],
[ 4, 5]])

Note that, here, c and a are totally independent copies.

Another big advantage of NumPy arrays is that the operations are propagated to the individual elements. For example, multiplying a NumPy array will result in an array of the same size (including all of its elements) being multiplied:

>>> d = np.array([1,2,3,4,5])
>>> d*2
array([ 2, 4, 6, 8, 10])

This is also true for other operations:

>>> d**2
array([ 1, 4, 9, 16, 25])

Contrast that with ordinary Python lists:

>>> [1,2,3,4,5]*2
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
>>> [1,2,3,4,5]**2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>

TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'

Of course, by using NumPy arrays, we sacrifice the agility Python lists offer. Simple operations, such as adding or removing elements, are a bit complex for NumPy arrays. Luckily, we have both at our hands, and we will use the right one for the task at hand.

主站蜘蛛池模板: 清流县| 洛宁县| 筠连县| 正阳县| 淄博市| 亚东县| 八宿县| 贵港市| 永定县| 呼和浩特市| 当涂县| 迭部县| 遂昌县| 庆安县| 五河县| 罗山县| 利津县| 平山县| 武平县| 赣榆县| 景泰县| 仪征市| 浙江省| 永宁县| 县级市| 蒙自县| 呈贡县| 临沧市| 潮州市| 乌拉特后旗| 宝应县| 云浮市| 呈贡县| 凌云县| 澜沧| 绿春县| 台前县| 页游| 北宁市| 祁门县| 五峰|