Home >Backend Development >Python Tutorial >Python Scientific Computing - Quick Start with Numpy

Python Scientific Computing - Quick Start with Numpy

高洛峰
高洛峰Original
2016-10-17 13:41:301658browse

What is Numpy?

Numpy is a scientific computing library for Python that provides matrix operation functions. It is generally used together with Scipy and matplotlib. It can be used to store and process large matrices and is much more efficient than Python's own nested list structure (which can also be used to represent matrices).


NumPy (Numeric Python) provides many advanced numerical programming tools, such as matrix data types, vector processing, and sophisticated operation libraries. Built for rigorous number crunching. It is mostly used by many large financial companies, as well as core scientific computing organizations such as Lawrence Livermore, and NASA uses it to handle some tasks that were originally done using C++, Fortran or Matlab.


Multidimensional array


The type of multidimensional array is: numpy.ndarray


Use the numpy.array method


to generate a one-dimensional array with list or tuple variables as parameters:

>>> print(np.array([1,2,3,4]))
[1 2 3 4]
>>> print(np.array((1.2,2,3,4)))
[ 1.2  2.   3.   4. ]
>>> print type(np.array((1.2,2,3,4)))
<type &#39;numpy.ndarray&#39;>


Generate a two-dimensional array with list or tuple variables as elements:

>>> print(np.array([[1,2],[3,4]]))
[[1 2]
 [3 4]]


Specify the data type

For example, numpy.int32, numpy.int16, and numpy.float64, etc.:

>>> print np.array((1.2,2,3,4), dtype=np.int32)
[1 2 3 4]
. Use the NUMPY.ARANGE method

>>> print(np.arange(15))
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
>>> print type(np.arange(15))
<type &#39;numpy.ndarray&#39;>
>>> print np.arange(15).reshape(3,5)
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
>>> print type(np.arange(15).reshape(3,5))
<type &#39;numpy.ndarray&#39;>

Use the numpy.linspace method

, for example, 9 numbers are generated from 1 to 3:

>>> print(np.linspace(1,3,10))
[ 1.          1.22222222  1.44444444  1.66666667  1.88888889  2.11111111
  2.33333333  2.55555556  2.77777778  3.        ]
E

Construct a specific matrix

Use numpy to use Numpy. .zeros, numpy.ones, numpy.eye

can construct a specific matrix

>>> print(np.zeros((3,4)))
[[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]
>>> print(np.ones((4,3)))
[[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]
>>> print(np.eye(4))
[[ 1.  0.  0.  0.]
 [ 0.  1.  0.  0.]
 [ 0.  0.  1.  0.]
 [ 0.  0.  0.  1.]]

Create a three-dimensional array:

>>> print(np.ones((3,3,3)))
[[[ 1.  1.  1.]
  [ 1.  1.  1.]
  [ 1.  1.  1.]]
 [[ 1.  1.  1.]
  [ 1.  1.  1.]
  [ 1.  1.  1.]]
 [[ 1.  1.  1.]
  [ 1.  1.  1.]
  [ 1.  1.  1.]]]

Get the properties of the array

>>> a = np.zeros((2,3,2))
>>> print(a.ndim)   #数组的维数
3
>>> print(a.shape)  #数组每一维的大小
(2, 3, 2)
>>> print(a.size)   #数组的元素数
12
>>> print(a.dtype)  #元素类型
float64
>>> print(a.itemsize)  #每个元素所占的字节数
8

Array index, slice, Assignment

>>>a = np.array( [[2,3,4],[5,6,7]] )
>>> print(a)
[[2 3 4]
 [5 6 7]]
>>> print(a[1,2]) #index从0开始
7
>>> print a[1,:]
[5 6 7]
>>> print(a[1,1:2])
[6]
>>> a[1,:] = [8,9,10] #直接赋值
>>> print(a)
[[ 2  3  4]
 [ 8  9 10]]

Use for to operate elements

>>> for x in np.linspace(1,3,3):
...     print(x)
...
1.0
2.0
3.0

Basic array operations

Construct arrays a and b first:

>>> a = np.ones((2,2))
>>> b = np.eye(2)
>>> print(a)
[[ 1.  1.]
 [ 1.  1.]]
>>> print(b)
[[ 1.  0.]
 [ 0.  1.]]

Addition and subtraction of arrays Use multiplication and division

>>> print(a > 2)
[[False False]
 [False False]]
>>> print(a+b)
[[ 2.  1.]
 [ 1.  2.]]
>>> print(a-b)
[[ 0.  1.]
 [ 1.  0.]]
>>> print(b*2)
[[ 2.  0.]
 [ 0.  2.]]
>>> print((a*2)*(b*2))
[[ 4.  0.]
 [ 0.  4.]]
>>> print(b/(a*2))
[[ 0.5  0. ]
 [ 0.   0.5]]
>>> print((b*2)**4)
[[ 16.  0]
 [ 0  16.]]

The method that comes with the array object

>>> a.sum() #a的元素个数
4.0
>>> a.sum(axis=0)   #计算每一列(二维数组中类似于矩阵的列)的和
array([ 2.,  2.])
>>> a.min()
1.0
>>> a.max()
1.0
使用numpy下的方法
>>> np.sin(a)
array([[ 0.84147098,  0.84147098],
       [ 0.84147098,  0.84147098]])
>>> np.max(a)
1.0
>>> np.floor(a)
array([[ 1.,  1.],
       [ 1.,  1.]])
>>> np.exp(a)
array([[ 2.71828183,  2.71828183],
       [ 2.71828183,  2.71828183]])
>>> np.dot(a,a)   ##矩阵乘法
array([[ 2.,  2.],
       [ 2.,  2.]])

Merge arrays

Use the vstack and hstack functions under numpy:

>>> a = np.ones((2,2))
>>> b = np.eye(2)
>>> print(np.vstack((a,b)))
#顾名思义 v--vertical  垂直
[[ 1.  1.]
 [ 1.  1.]
 [ 1.  0.]
 [ 0.  1.]]
>>> print(np.hstack((a,b)))
#顾名思义 h--horizonal 水平
[[ 1.  1.  1.  0.]
 [ 1.  1.  0.  1.]]

Let’s see if these two functions involve the problem of shallow copy:

>>> c = np.hstack((a,b))
>>> print c
[[ 1.  1.  1.  0.]
 [ 1.  1.  0.  1.]]
>>> a[1,1] = 5
>>> b[1,1] = 5
>>> print c
[[ 1.  1.  1.  0.]
 [ 1.  1.  0.  1.]]

It can be seen that the change of elements in a and b does not affect c.


Deep copy array

Array objects come with shallow copy and deep copy methods, but generally deep copy is more common:

>>> a = np.ones((2,2))
>>> b = a
>>> print(b is a)
True
>>> c = a.copy()  #深拷贝
>>> c is a
False

Basic matrix operations

Transpose:

>>> a = np.array([[1,0],[2,3]])
>>> print(a)
[[1 0]
 [2 3]]
>>> print(a.transpose())
[[1 2]
 [0 3]]

numpy.linalg About matrix operation methods

>>> import numpy.linalg as nplg1

Eigenvalues, eigenvectors:

>>> print nplg.eig(a)
(array([ 3.,  1.]), array([[ 0.        ,  0.70710678],
       [ 1.        , -0.70710678]]))


Matrix object

The matrix object in the numpy module is numpy.matrix, including matrices Data processing, matrix calculations, and basic statistical functions, transposition, reversibility, etc., including the processing of complex numbers, are all in the matrix object.


class numpy.matrix(data,dtype,copy):


Returns a matrix, where data is an ndarray object or character form;


dtype: is the type of data;


copy: is bool type.

>>> a = np.matrix(&#39;1 2 7; 3 4 8; 5 6 9&#39;)
>>> a             #矩阵的换行必须是用分号(;)隔开,内部数据必须为字符串形式(‘ ’),矩
matrix([[1, 2, 7],       #阵的元素之间必须以空格隔开。
[3, 4, 8],
[5, 6, 9]])
>>> b=np.array([[1,5],[3,2]])
>>> x=np.matrix(b)   #矩阵中的data可以为数组对象。
>>> x
matrix([[1, 5],
[3, 2]])

Properties of the matrix object

matrix.T transpose

: Returns the transpose matrix of the matrix


matrix.H hermitian (conjugate) transpose

: Returns the conjugate element matrix of the complex matrix


matrix.I inverse

: Returns the inverse matrix of the matrix


matrix.

all ([axis, out]): Determine whether all elements of the matrix are true along the given axis (non-0 means true)


any([axis, out]): Determine the matrix elements along the direction of the given axis Whether it is true or not is true as long as one element is true.


argmax([axis, out]) : Returns the index of the largest element (the position of the largest element) along the direction of the given axis.


argmin([axis, out]) : Along the given axis The direction returns the index of the smallest element (the position of the smallest element)


argsort([axis, kind, order]) : returns the sorted index matrix


astype(dtype[, order, casting, subok , copy]): Copy the matrix data, and the data type is the specified data type


byteswap(inplace) Swap the bytes of the array elements


choose(choices[, out, mode]) : Get a new data matrix according to the given index (the index is given from choices)


clip(a_min, a_max[, out]) : Return the new matrix, the element larger than the given element is a_max, The small one is a_min


compress(condition[, axis, out]): Returns the matrix that satisfies the condition


conj() :返回复数的共轭复数


conjugate() :返回所有复数的共轭复数元素


copy([order]) :复制一个矩阵并赋给另外一个对象,b=a.copy()


cumprod([axis, dtype, out]) :返回沿指定轴的元素累积矩阵


cumsum([axis, dtype, out]) :返回沿指定轴的元素累积和矩阵


diagonal([offset, axis1, axis2]) :返回矩阵中对角线的数据


dot(b[, out]) :两个矩阵的点乘


dump(file) :将矩阵存储为指定文件,可以通过pickle.loads()或者numpy.loads()如:a.dump(‘d:\a.txt’)


dumps() :将矩阵的数据转存为字符串.


fill(value) :将矩阵中的所有元素填充为指定的value


flatten([order]) :将矩阵转化为一个一维的形式,但是还是matrix对象


getA() :返回自己,但是作为ndarray返回


getA1():返回一个扁平(一维)的数组(ndarray)


getH() :返回自身的共轭复数转置矩阵


getI() :返回本身的逆矩阵


getT() :返回本身的转置矩阵


max([axis, out]) :返回指定轴的最大值


mean([axis, dtype, out]) :沿给定轴方向,返回其均值


min([axis, out]) :返回指定轴的最小值


nonzero() :返回非零元素的索引矩阵


prod([axis, dtype, out]) :返回指定轴方型上,矩阵元素的乘积.


ptp([axis, out]) :返回指定轴方向的最大值减去最小值.


put(indices, values[, mode]) :用给定的value替换矩阵本身给定索引(indices)位置的值


ravel([order]) :返回一个数组,该数组是一维数组或平数组


repeat(repeats[, axis]) :重复矩阵中的元素,可以沿指定轴方向重复矩阵元素,repeats为重复次数


reshape(shape[, order]) :改变矩阵的大小,如:reshape([2,3])


resize(new_shape[, refcheck]) :改变该数据的尺寸大小


round([decimals, out]) :返回指定精度后的矩阵,指定的位数采用四舍五入,若为1,则保留一位小数


searchsorted(v[, side, sorter]) :搜索V在矩阵中的索引位置


sort([axis, kind, order]) :对矩阵进行排序或者按轴的方向进行排序


squeeze([axis]) :移除长度为1的轴


std([axis, dtype, out, ddof]) :沿指定轴的方向,返回元素的标准差.


sum([axis, dtype, out]) :沿指定轴的方向,返回其元素的总和


swapaxes(axis1, axis2):交换两个轴方向上的数据.


take(indices[, axis, out, mode]) :提取指定索引位置的数据,并以一维数组或者矩阵返回(主要取决axis)


tofile(fid[, sep, format]) :将矩阵中的数据以二进制写入到文件


tolist() :将矩阵转化为列表形式


tostring([order]):将矩阵转化为python的字符串.


trace([offset, axis1, axis2, dtype, out]):返回对角线元素之和


transpose(*axes) :返回矩阵的转置矩阵,不改变原有矩阵


var([axis, dtype, out, ddof]) :沿指定轴方向,返回矩阵元素的方差


view([dtype, type]) :生成一个相同数据,但是类型为指定新类型的矩阵。


举例

>>> a = np.asmatrix(&#39;0 2 7; 3 4 8; 5 0 9&#39;)
>>> a.all()
False
>>> a.all(axis=0)
matrix([[False, False,  True]], dtype=bool)
>>> a.all(axis=1)
matrix([[False],
[ True],
[False]], dtype=bool)

   

Astype方法

>>> a.astype(float)
matrix([[ 12.,   3.,   5.],
[ 32.,  23.,   9.],
[ 10., -14.,  78.]])

   

Argsort方法

>>> a=np.matrix(&#39;12 3 5; 32 23 9; 10 -14 78&#39;)
>>> a.argsort()
matrix([[1, 2, 0],
[2, 1, 0],
[1, 0, 2]])

   

Clip方法

>>> a
matrix([[ 12,   3,   5],
[ 32,  23,   9],
[ 10, -14,  78]])
>>> a.clip(12,32)
matrix([[12, 12, 12],
[32, 23, 12],
[12, 12, 32]])

   


Cumprod方法

 
>>> a.cumprod(axis=1)
matrix([[    12,     36,    180],
[    32,    736,   6624],
[    10,   -140, -10920]])

   

Cumsum方法

>>> a.cumsum(axis=1)
matrix([[12, 15, 20],
[32, 55, 64],
[10, -4, 74]])

   


Tolist方法

>>> b.tolist()
[[12, 3, 5], [32, 23, 9], [10, -14, 78]]

Tofile方法

>>> b.tofile(&#39;d:\\b.txt&#39;)

   

compress()方法

>>> from numpy import *

>>> a = array([10, 20, 30, 40])
>>> condition = (a > 15) & (a < 35)
>>> condition
array([False, True, True, False], dtype=bool)
>>> a.compress(condition)
array([20, 30])
>>> a[condition]                                      # same effect
array([20, 30])
>>> compress(a >= 30, a)                              # this form a
so exists
array([30, 40])
>>> b = array([[10,20,30],[40,50,60]])
>>> b.compress(b.ravel() >= 22)
array([30, 40, 50, 60])
>>> x = array([3,1,2])
>>> y = array([50, 101])
>>> b.compress(x >= 2, axis=1)                       # illustrates 
the use of the axis keyword
array([[10, 30],
[40, 60]])
>>> b.compress(y >= 100, axis=0)
array([[40, 50, 60]])

   


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn