Numpy starter tutorial in Python

  • 2020-04-02 13:35:27
  • OfStack

1. What is Numpy

Quite simply, Numpy is a library for scientific computing in Python, providing the functionality of matrix operations, which is commonly used in conjunction with Scipy and matplotlib. List already provides a matrix-like representation, but numpy gives us more functions. If you have been exposed to matlab, scilab, then numpy is a good start. In the following code example, numpy is always preloaded:


>>> import numpy as np
>>> print np.version.version
1.6.2


2. Multidimensional array

The type of the multidimensional array is: numpy.ndarray.

Use the numpy.array method

A one-dimensional array is generated by taking a list or tuple variable as a parameter:

>>> 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 'numpy.ndarray'>

To generate a two-dimensional array with a list or tuple variable as an element:

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

When an array is generated, you can specify the data types, such as numpy.int32, numpy.int16, and numpy.float64:

>>> 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 'numpy.ndarray'>
>>> 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 'numpy.ndarray'>

Use the numpy.linspace method

For example, generate 9 Numbers from 1 to 3:


>>> print np.linspace(1,3,9)
[ 1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.  ]

Specific matrices can be constructed using methods such as numpy.zeros, numpy.ones, and numpy.eye

Such as:


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

Create a 3d array:

>>> print np.zeros((2,2,2))
[[[ 0.  0.]
  [ 0.  0.]]
 [[ 0.  0.]
  [ 0.  0.]]]

Get array properties:

>>> a = np.zeros((2,2,2))
>>> print a.ndim   # The number of dimensions of an array 
3
>>> print a.shape  # The size of each dimension of the array 
(2, 2, 2)
>>> print a.size   # The number of elements in an array 
8
>>> print a.dtype  # The element type 
float64
>>> print a.itemsize  # The number of bytes per element 
8


Array index, slice, assign

Example:


>>> a = np.array( [[2,3,4],[5,6,7]] )
>>> print a
[[2 3 4]
 [5 6 7]]
>>> print a[1,2]
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 the for action element

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


Basic array operations

First, construct arrays a and b:


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

Array addition, subtraction, 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 (a*2)**4
[[ 16.  16.]
 [ 16.  16.]]

  Using methods that come with array objects:


>>> a.sum()
4.0
>>> a.sum(axis=0)   # Calculate the sum of each column (a matrix-like column in a two-dimensional array) 
array([ 2.,  2.])
>>> a.min()
1.0
>>> a.max()
1.0

Using the method under 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)   ## Matrix multiplication 
array([[ 2.,  2.],
       [ 2.,  2.]])


Merge array

Use the vstack and hstack functions under numpy:


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

Let's see if these two functions involve shallow copying:


>>> 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.]]

As you can see, 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 there are usually more deep-copy methods:

>>> a = np.ones((2,2))
>>> b = a
>>> b is a
True
>>> c = a.copy()  # Deep 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]]

Mark:
>>> print np.trace(a)
4

The numpy.linalg module has a number of methods for matrix operations:

>>> import numpy.linalg as nplg

Eigenvalues and eigenvectors:


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

3, matrix

Numpy can also construct matrix objects, which I won't discuss here.


Related articles: