Sitemap
Biresh Kumar Singh

Biresh Kumar Singh

latest tech and learning about yourself https://birulabs.com

Everything You Need to Know About NumPy (With Code)

6 min readAug 12, 2026

--

Source : https://www.includehelp.com/python/how-does-the-axis-parameter-from-numpy-work.aspx

It is building block of so many libraries like Scikit-learn, Pandas etc. It helps to interact with multi dimensional arrays called ndarray. People love NumPy because it is fast. NumPy arrays use contiguous blocks of memory that can be efficiently cached by the CPU. In contrast, Python lists are arrays of pointers to objects in random locations in memory, which cannot be easily cached and come with a more expensive memory-look-up.

Press enter or click to view image in full size

NumPy infers the datatype of elements upon construction.
We can also change the dtype while constructcing the array using array function :

Press enter or click to view image in full size

Once an array has been constructed, we can downcast or recast its type withthe astype method:

Press enter or click to view image in full size

We can use size to get the number of elements in an array and ndim for number of dimensions in our array.

Press enter or click to view image in full size

We can also find shape like if a 2D array has 2 rows and 3 columns , then shape will be (2,3).

Press enter or click to view image in full size

Array Construction Functions

There are many array construction functions that we can use like creating arrays of ones or zeros can be useful as placeholder arrays and we can also create identity maatrices and diagonal matrices.

Press enter or click to view image in full size

Also, we can use arange function to create an array(Its behavior is similar to that of the range function in python) :

Press enter or click to view image in full size

Also we use linspace function if we want to create a particular number of evenly spaced values in a specified half-open interval:

Array Indexing

Remember : If we work with arrays that have more than one dimension or axis, we separate our indexing or slicing operations by commas.

You need to understand axes before this:

Source : https://www.statology.org/numpy-axis/

To do indexing and slicing in one cmd, we do something like this:
ary[a:b,c:d]

Now here, first value before comma is for rows and second value after comma is for column and then you just apply slicing and give results, See this examples :

Press enter or click to view image in full size

Array Math and Universal Functions

One of the core features of NumPy is vectorization because it makes working with ndarrays really efficient. NumPy provides vectorized wrappers for performing element-wise operations if we want to perform arithmetic operations on sequence-like objects — these are called ufuncs.

The ufuncs for basic arithmetic operations are add, subtract, divide, multiply, power, and exp (exponential). However, NumPy uses operator overloading so that we can use mathematical operators (+, -, /, *, and **) directly.

Lets see some unary ufuncs such as log (natural logarithm), log10 (base-10 logarithm), and sqrt (square root) and some binary ufuncs :

Press enter or click to view image in full size

Reduce and Sum

With the help fo reduce, we can compute any operation like sum or product along an axis and reduce the array. While it can be more intuitive to use reduce as a more general operation, NumPy also provides shorthands for specific operations such as product and sum. For example, sum(axis=0) is equivalent to add.reduce . See examples :

Press enter or click to view image in full size

Kindly see this , you will have a better understanding of what I am talking about:

Press enter or click to view image in full size
Source : https://practicaldatascience.org/notebooks/class_2/week_4/03_summarizing_arrays.html

So, the things that we did just now is known as Broadcasting. Broadcasting allows us to perform vectorized operations between two arrays even if their dimensions do not match by creating implicit multidimensional grids. ufuncs is one example of Broadcasting. See this :

Press enter or click to view image in full size
Source : https://blog.finxter.com/numpy-broadcasting-a-simple-tutorial/

Advanced Indexing — Memory Views and Copies

Remember — It is important to note that basic integer-based indexing and slicing create so-called views of NumPy arrays in memory. Also, whenever you change something in views, the original array is also modified.

Press enter or click to view image in full size

But if you don’t want to modify the original array, you have to use the copy() method :

Press enter or click to view image in full size

Fancy Indexing

We can use tuple or list objects of non-contiguous integer indices to return desired array elements :

Press enter or click to view image in full size

Boolean Masks for Indexing

We can also use Boolean masks for indexing — that is, arrays of True and False values. Consider the following example, where we return all values in the array that are greater than 3:

Press enter or click to view image in full size

Random Number Generators

A computer doesn’t normally generate truly random numbers. NumPy uses a pseudo-random number generator (PRNG).

Get Biresh Kumar Singh’s stories in your inbox

Join Medium for free to get updates from this writer.

Remember — We first seed NumPy’s random number generator. Then, we draw random samples from a uniform distribution via random.rand in the half-open interval [0, 1).

Press enter or click to view image in full size

But lets say, we have two functions :

def generate_data():
return np.random.rand(3)

def generate_noise():
return np.random.rand(3)

So, both functions are using the same global random generator and lets say, we execute both functions:

generate_data()
generate_noise()

Then :

Global RNG
│
├── generate_data() → consumes 3 random numbers
│
└── generate_noise() → consumes the NEXT 3 numbers

Now suppose you change generate_data() and it consumes 5 random numbers instead of 3. Suddenly generate_noise() gets completely different numbers.

That’s annoying for testing.

To solve this, we use Separate RandomState objects

rng_data = np.random.RandomState(100)
rng_noise = np.random.RandomState(200)

Now you have:

rng_data
↓
its own random sequence


rng_noise
↓
a completely separate random sequence

They don't interfere with each other.

Reshaping NumPy Arrays

NumPy provides a reshape methods that allow us to obtain a view of an array with a different shape.

Press enter or click to view image in full size

We do not need to specify the number elements in each axis; NumPy is smart enough to figure out how many elements to put along an axis if only one axis is unspecified (by using the placeholder -1):

Press enter or click to view image in full size

Flattening the array using reshape:

NumPy’s Concate Function to merge two arrays :
Remember : axis = 0 means rows and axis = 1 means columns

Press enter or click to view image in full size

Linear Algebra with NumPy

To perform matrix multiplication between matrices, we learned that number of columns of the left matrix must match the number of rows of the matrix to the right. In NumPy, we can perform matrix multiplication via the matmul function.

Also, NumPy can be quite forgiving if the dimensions of matrices and one-dimensional arrays do not match exactly — thanks to broadcasting.

Press enter or click to view image in full size

NumPy has a special dot function that behaves similar to matmul on pairs of one- or two-dimensional arrays or we can also use @ :

Transpose :

Press enter or click to view image in full size

Thank you for reading till here

--

--