Everything You Need to Know About NumPy (With Code)
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.
NumPy infers the datatype of elements upon construction.
We can also change the dtype while constructcing the array using array function :
Once an array has been constructed, we can downcast or recast its type withthe astype method:
We can use size to get the number of elements in an array and ndim for number of dimensions in our array.
We can also find shape like if a 2D array has 2 rows and 3 columns , then shape will be (2,3).
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.
Also, we can use arange function to create an array(Its behavior is similar to that of the range function in python) :
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:
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 :
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 :
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 :
Kindly see this , you will have a better understanding of what I am talking about:
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 :
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.
But if you don’t want to modify the original array, you have to use the copy() method :
Fancy Indexing
We can use tuple or list objects of non-contiguous integer indices to return desired array elements :
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:
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).
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 sequenceThey 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.
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):
Flattening the array using reshape:
NumPy’s Concate Function to merge two arrays :
Remember : axis = 0 means rows and axis = 1 means columns
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.
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 :










