You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
np.array([2, 3, 4]) # direct initializationnp.empty(20, dtype=np.float32) # single precision array of size 20np.zeros(200) # initialize 200 zerosnp.ones((3,3), dtype=np.int32) # 3 x 3 integer matrix with onesnp.eye(200) # ones on the diagonalnp.zeros_like(a) # array with zeros and the shape of anp.linspace(0., 10., 100) # 100 points from 0 to 10np.arange(0, 100, 2) # points from 0 to <100 with step 2np.logspace(-5, 2, 100) # 100 log-spaced from 1e-5 -> 1e2np.copy(a) # copy array to new memory
indexing
a=np.arange(100) # initialization with 0 - 99a[:3] =0# set the first three indices to zeroa[2:5] =1# set indices 2-4 to 1a[:-3] =2# set all but last three elements to 2a[start:stop:step] # general form of indexing/slicinga[None, :] # transform to column vectora[[1, 1, 3, 8]] # return array with values of the indicesa=a.reshape(10, 10) # transform to 10 x 10 matrixa.T# return transposed viewb=np.transpose(a, (1, 0)) # transpose array to new axis ordera[a<2] # values with elementwise condition
array properties and operations
a.shape# a tuple with the lengths of each axislen(a) # length of axis 0a.ndim# number of dimensions (axes)a.sort(axis=1) # sort array along axisa.flatten() # collapse array to one dimensiona.conj() # return complex conjugatea.astype(np.int16) # cast to integera.tolist() # convert (possibly multidimensional) array to listnp.argmax(a, axis=1) # return index of maximum along a given axisnp.cumsum(a) # return cumulative sumnp.any(a) # True if any element is Truenp.all(a) # True if all elements are Truenp.argsort(a, axis=1) # return sorted index array along axisnp.where(cond) # return indices where cond is Truenp.where(cond, x, y) # return elements from x or y depending on cond
a*5# multiplication with scalara+5# addition with scalara+b# addition with array ba/b# division with b (np.NaN for division by zero)np.exp(a) # exponential (complex and real)np.power(a, b) # a to the power bnp.sin(a) # sinenp.cos(a) # cosinenp.arctan2(a, b) # arctan(a/b)np.arcsin(a) # arcsinnp.radians(a) # degrees to radiansnp.degrees(a) # radians to degreesnp.var(a) # variance of arraynp.std(a, axis=1) # standard deviation
inner/ outer products
np.dot(a, b) # inner product: a_mi b_innp.einsum('ij,kj->ik', a, b) # einstein summation conventionnp.sum(a, axis=1) # sum over axis 1np.abs(a) # return absolute valuesa[None, :] +b[:, None] # outer suma[None, :] *b[:, None] # outer productnp.outer(a, b) # outer productnp.sum(a*a.T) # matrix norm
linear algebra/ matrix math
evals, evecs=np.linalg.eig(a) # Find eigenvalues and eigenvectorsevals, evecs=np.linalg.eigh(a) # np.linalg.eig for hermitian matrix
reading/ writing files
np.loadtxt(fname/fobject, skiprows=2, delimiter=',') # ascii data from filenp.savetxt(fname/fobject, array, fmt='%.5f') # write ascii datanp.fromfile(fname/fobject, dtype=np.float32, count=5) # binary data from filenp.tofile(fname/fobject) # write (C) binary datanp.save(fname/fobject, array) # save as numpy binary (.npy)np.load(fname/fobject, mmap_mode='c') # load .npy file (memory mapped)
interpolation, integration, optimization
np.trapz(a, x=x, axis=1) # integrate along axis 1np.interp(x, xp, yp) # interpolate function xp, yp at points xnp.linalg.lstsq(a, b) # solve a x = b in least square sense
rounding
np.ceil(a) # rounds to nearest upper intnp.floor(a) # rounds to nearest lower intnp.round(a) # rounds to neares int
random variables
fromnp.randomimportnormal, seed, rand, uniform, randintnormal(loc=0, scale=2, size=100) # 100 normal distributedseed(23032) # resets the seed valuerand(200) # 200 random numbers in [0, 1)uniform(1, 30, 200) # 200 random numbers in [1, 30)randint(1, 16, 300) # 300 random integers in [1, 16)
Matplotlib
figures and axes
fig=plt.figure(figsize=(5, 2)) # initialize figurefig.savefig('out.png') # save png imagefig, axes=plt.subplots(5, 2, figsize=(5, 5)) # fig and 5 x 2 nparray of axesax=fig.add_subplot(3, 2, 2) # add second subplot in a 3 x 2 gridax=plt.subplot2grid((2, 2), (0, 0), colspan=2) # multi column/row axisax=fig.add_axes([left, bottom, width, height]) # add custom axis
figures and axes properties
fig.suptitle('title') # big figure titlefig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,
hspace=0.5) # adjust subplot positionsfig.tight_layout(pad=0.1, h_pad=0.5, w_pad=0.5,
rect=None) # adjust subplots to fit into figax.set_xlabel('xbla') # set xlabelax.set_ylabel('ybla') # set ylabelax.set_xlim(1, 2) # sets x limitsax.set_ylim(3, 4) # sets y limitsax.set_title('blabla') # sets the axis titleax.set(xlabel='bla') # set multiple parameters at onceax.legend(loc='upper center') # activate legendax.grid(True, which='both') # activate gridbbox=ax.get_position() # returns the axes bounding boxbbox.x0+bbox.width# bounding box parameters
# interpolate data at index positions:fromscipy.ndimageimportmap_coordinatespts_new=map_coordinates(data, float_indices, order=3)
# simple 1d interpolator with axis argument:fromscipy.interpolateimportinterp1dinterpolator=interp1d(x, y, axis=2, fill_value=0., bounds_error=False)
y_new=interpolator(x_new)
Integration
fromscipy.integrateimportquad# definite integral of pythonvalue=quad(func, low_lim, up_lim) # function/method
linear algebra
fromscipyimportlinalgevals, evecs=linalg.eig(a) # Find eigenvalues and eigenvectorsevals, evecs=linalg.eigh(a) # linalg.eig for hermitian matrixb=linalg.expm(a) # Matrix exponentialc=linalg.logm(a) # Matrix logarithm