Python Numerical Computing Extensions - NumPy


1. Introduction to
NumPy The NumPy system is an open source numerical computing extension to Python. This tool can be used to store and process large matrices much more efficiently than Python's own nested list structure (which can also be used to represent matrices).

The following is the official English introduction:
NumPy is the fundamental package for scientific computing with Python. It contains among other things:

(1)a powerful N-dimensional array object
(2)sophisticated (broadcasting) functions
(3)tools for integrating C/C++ and Fortran code
(4)useful linear algebra, Fourier transform, and random number capabilities

Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases.

2. Notes on the python environment
At present, python3 is used more frequently. Some students may have installed two versions, including python2. After the Mac enters the python command in the terminal, the output information is still Python 2.7.
How to make the system use python3 by default? Follow the steps below to set it up:
(1) Enter the terminal: open ~/.bash_profile to open the .bash_profile file.
(2) Modify the content of the .bash_profile file and add the following two lines: PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}"
export PATH (3)添加别名 alias python=``"/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6"
(4) Re-validate the .bash_profile file
source .bash_profile

After the above four steps, enter phtyon in the terminal, and the following content appears, the modification is successful.



3. NumPy installation
After configuring the python environment, enter: from numpy import* on the command line. If the following error is prompted, we need to install NumPy manually:



(1) pip installation
We use pip to install NumPy, provided that pip has been installed, and pip is not installed by default on mac.
If you are using the python2.7 that comes with macOS, directly enter the terminal: sudo easy_install pip to install.
If you are using Python3, type in the terminal: curl  https://bootstrap.pypa.io/get-pip.py  | python3.
After the installation is complete, check the version and path of pip. Since I installed python2 and 3 respectively, I also installed different versions of pip as follows:



Note:
1) The newly installed library using pip install XXX
will be placed in this directory
python2.7/site-packages

2) The newly installed library using pip3 install XXX
will be placed in this directory
python3.6/site-packages

When using python3 to execute the program, then you cannot import the library in python2.7/site-packages.

(2) Install NumPy
terminal input: sudo pip3 install -U numpy
installation successfully outputs the following log:



Fourth, NumPy use
(1)
The main object of the basic NumPy is the same type of multidimensional array. It is a table with all elements (usually numbers) of the same type and indexed by a tuple of positive integers. In NumPy, dimensions are called axes. The number of axes is rank.

For example, the coordinates [1, 2, 1] of a point in 3D space is an array with rank 1 because it has one axis. The length of this axis is 3. In the example shown in the image below, the array has a rank of 2 (it is 2-dimensional). The first dimension (axis) has length 2 and the second dimension has length 3.

[[ 1., 0., 0.],
[ 0., 1., 2.]]
The class of NumPy arrays is called ndarray. aliased to array. Note that numpy.array differs from the standard Python library's class array.array, which only deals with one-dimensional arrays and provides less functionality. The more important properties of ndarray objects are:


The number of axes (dimensions) of the ndarray.ndim array. In the Python world, the number of dimensions is called a rank.
ndarray.shape
The dimensions of the array. This is a tuple of integers representing the size of the array in each dimension. For a matrix with n rows and m columns, the shape will be (n,m). Therefore, the length of the shape tuple is the number of rank or dimension ndim.
ndarray.size
The total number of array elements. This is equal to the product of the elements of shape.
ndarray.dtype
is an object describing the type of the elements in the array. A dtype can be created or specified using standard Python types. Additionally NumPy provides its own types. For example numpy.int32, numpy.int16 and numpy.float64.
ndarray.itemsize
The size in bytes of each element in the array. For example, an array with elements of type float64 has an itemsize of 8 (=64/8), and an array of type complex32 has a comitemsize of 4 (=32/8). It is equal to ndarray.dtype.itemsize.
ndarray.data
This buffer contains the actual elements of the array. Usually, we don't need to use this property because we will use the index to access the elements in the array.

for example:

import numpy as np

#这里我们生成了一个一维数组a,从0开始,步长为1,长度为20
a = np.arange(15)
print('a:',a)

#打印a的类型,应该是array
print('a type:',type(a))

#通过函数"reshape",我们可以重新构造一下这个数组,例如,我们可以构造一个3*5的二维数组
a = a.reshape(3, 5)
print('a.reshape:',a)

#数组的维度
print('a.shape:',a.shape)

#数组的维度的个数
print('a.ndim:',a.ndim)

#数组元素总数
print('a.size:',a.size)

#数组元素类型
print('a.dtype:',a.dtype)

#数组元素的字节大小
print('a.itemsize:',a.itemsize)

The corresponding output is as follows:

a: [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
a type: <class 'numpy.ndarray'>
a.reshape: [[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
a.shape: (3, 5)
a.ndim: 2
a.size: 15
a.dtype: int64
a.itemsize: 8

(2) Array Creation
There are several ways to create an array. You can use the array function to create an array from a regular Python list or tuple. The type of the resulting array is deduced from the types of the elements in the sequence.

>>> a = array( [2,3,4] )
>>> a
array([2, 3, 4])
>>> a.dtype
dtype('int32')
>>> b = array([1.2, 3.5, 5.1])
>>> b.dtype
dtype('float64')  一个常见的错误包括用多个数值参数调用`array`而不是提供一个由数值组成的列表作为一个参数。

>>> a = array(1,2,3,4)    # WRONG

>>> a = array([1,2,3,4])  # RIGHT

(3) Array printing
When you print an array, NumPy displays it like a nested list, but in the following layout:

最后的轴从左到右打印
次后的轴从顶向下打印
剩下的轴从顶向下打印,每个切片通过一个空行与下一个隔开
一维数组被打印成行,二维数组成矩阵,三维数组成矩阵列表。

>>> a = arange(6)                         # 1d array
>>> print a
[0 1 2 3 4 5]
>>>
>>> b = arange(12).reshape(4,3)           # 2d array
>>> print b
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
>>>
>>> c = arange(24).reshape(2,3,4)         # 3d array
>>> print c
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

(4)数组运算
数组上的算术运算符使用元素级别。将创建一个新数组并用结果填充。

>>> a = np.array( [20,30,40,50] )
>>> b = np.arange( 4 )
>>> b
array([0, 1, 2, 3])
>>> c = a-b
>>> c
array([20, 29, 38, 47])
>>> b**2
array([0, 1, 4, 9])
>>> 10*np.sin(a)
array([ 9.12945251, -9.88031624,  7.4511316 , -2.62374854])
>>> a<35
array([ True, True, False, False], dtype=bool)

与许多矩阵语言不同,乘法运算符*的运算在NumPy数组中是元素级别的。可以使用dot函数或方法执行矩阵乘积:

>>> A = np.array( [[1,1],
...             [0,1]] )
>>> B = np.array( [[2,0],
...             [3,4]] )
>>> A*B                         # elementwise product
array([[2, 0],
       [0, 4]])
>>> A.dot(B)                    # matrix product
array([[5, 4],
       [3, 4]])
>>> np.dot(A, B)                # another matrix product
array([[5, 4],
       [3, 4]])

某些操作(如+=和*=)可以修改现有数组,而不是创建新数组。

>>> a = np.ones((2,3), dtype=int)
>>> b = np.random.random((2,3))
>>> a *= 3
>>> a
array([[3, 3, 3],
       [3, 3, 3]])
>>> b += a
>>> b
array([[ 3.417022  ,  3.72032449,  3.00011437],
       [ 3.30233257,  3.14675589,  3.09233859]])
>>> a += b                  # b is not automatically converted to integer type
Traceback (most recent call last):
  ...
TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int64') with casting rule 'same_kind'

此外,NumPy还有很多强大的功能,大家如果有需要可以到官方参考文档。


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325721164&siteId=291194637