In this post I will document certain things I’ve learned when working with numpy. Might be interesting to some people.

Table of Contents

Axes in numpy

Axes in numpy are defined for arrays in more than one dim. A 2D array has the 0th axis running vertically downwards across rows and the 1st axis is running horizontally running across columns.



The numpy.printoptions function can be used for setting various global print options like linewidth and precision during printing to console. Useful for debugging and viewing:

  • suppress - Suppress printing in scientific notation.
  • precision - Limit the precision of numbers printed.
  • linewidth - Max width of printing.


The pdb module is useful for debugging python. Place pdb.set_trace() in some place in the code where you want the code to break. It will then provide you with a python REPL.

Here’s a link to it:


Numpy uses ‘broadcastable’ data structures. It describes how numpy treats arrays with different shapes during arithmetic operations.



Shape parameters

Sometimes, some operations return their shape at (R,1) and some as (R,). This design decision is taken because numpy arrays are indexed by two numbers in the former case and a single number in the latter case. This allows single number indexing and storage in flat-indexed arrays.


Useful functions

Setting diagonals

Use numpy.fill_diagonal() for filling the diagonal of an array with some number. Take note that this is an in-place modification function and that it does not return any value.


Matrix lower triangle

Use numpy.tril() and pass the object.

Inverse of a matrix

Compute multiplicative inverse of a matrix using numpy.linalg.inv().



* is element-wise multiplication between two arrays. For matrix multiplication use numpy.matmul.