A Selection of Useful Numpy Core Functions: Greg Von Winckel
A Selection of Useful Numpy Core Functions: Greg Von Winckel
April 2, 2014
array
array is the basic data type handled by all NumPy functions.
array(object, dtype=None, copy=True, order=None,
subok=False, ndmin=0)
Usually constructed from list or tuple.
All elements have the same type (e.g. bool, int, complex,
float, or str.)
In [6]: np.transpose(A)
Out[6]:
array([[0, 1],
.......[2, 3],
.......[4, 5]])
In [7]: print(A.T)
[[0, 1],
[2, 3],
[4, 5]]
In [7]: np.diagonal([1,2])
Out[7]:
array([[1, 0],
.......[0, 2]])
In [8]: np.diagonal([1,2],1)
Out[8]:
array([[0, 1, 0],
.......[0, 0, 2],
.......[0, 0, 0]])
In [4]: np.diff(A,1,0)
Out[4]:
array([[-1, 2, 0],
.......[0, -2, 3]])
In [5]: np.diff(A,2,1)
Out[5]:
array([[ 1],
.......[-4],
.......[ 3]]
Core NumPy Functions
In [5]: A=np.array(((1,2),(1,2)))
In [6]: np.dot(A,A)
Out[6]:
array([[3, 6],
.......[3, 6]])
In [7]: np.inner(A,A)
Out[7]:
array([[5, 5],
.......[5, 5]])
np.dot(A,A.T) produces the same
output as as np.inner(A,A).
In [3]: np.eye(2,2,-1,dtype=bool)
Out[3]:
array([[False, False],
.......[ True, False]], dtype=bool)
In [4]: np.eye(3,2,dtype=int)
Out[4]:
array([[1, 0],
.......[0, 1],
.......[0, 0]])
histogram
This function compartmentalizes an array of data into bins
polyval(p,x)
roots(p)
The three core polynomial functions fit data with polynomials,
evaluate polynomials on a grid, and compute roots of polynomials
In [1]: x=np.linspace(-1,1,5)
In [2]: f=1-np.exp(-x)
In [3]: p=np.polyfit(x,f,3)
In [4]: np.set printoptions(precision=4,linewidth=80)
In [5]: print(f)
[-1.7183 -0.6487 0. 0.3935 0.6321]
In [6]: print(np.polyval(p,x))
[-1.7174 -0.6524 0.0056 0.3897 0.6331]
In [7]: print(np.roots(p))
[ 1.5470+1.8029j 1.5470-1.8029j -0.0056+0.j ]
Greg von Winckel
In [1]: np.repeat([0,1,2,3],[3,2,1,0])
Out[1]: array([0, 0, 0, 1, 1, 2])
In [2]: np.tile([1,0],(2,2,3))
Out[2]:
array([[[1, 0, 1, 0, 1, 0],
.........[1, 0, 1, 0, 1, 0]],
blank
.........[[1, 0, 1, 0, 1, 0],
.........[1, 0, 1, 0, 1, 0]]])
In [4]: A=np.tile([1,2,3],(3,1))
In [5]: np.mean(A,0)
Out[5]: array([ 1., 2., 3.])
In [6]: np.mean(A,1)
Out[6]: array([ 2., 2., 2.])
In [7]: np.std(A,0)
Out[7]: array([ 0., 0., 0.])