Mastering NumPy: Initializing Ways, Ndarray Operations & Functions

# Mastering NumPy: Initializing Ways, Ndarray Operations & Functions

Last updated:
5th Jan, 2021
Views
5 Mins
View All

Numpy is a Python package that allows mathematical and numerical operations to be performed with high-efficiency and abstract functionality on high-dimensional data. While building a Machine Learning solution for a particular business use case, it becomes very important to transform the data in such a way that the preprocessing becomes easy, and the results are interpretable. Numpy is the core library that makes it possible to perform all the related functions in the best possible way.

## Why NumPy?

Other Data Science libraries such as Pandas, Matplotlib, and Scikit-learn are built on top of Numpy because of its high-performance nature. This library offers ndarray which is used in place of inbuilt python lists. Python list is great to store values, but it comes at the cost of increased execution time as it stores pointers of the memory locations which adds overhead in terms of memory and execution.

Numpy finds its direct usage in the image processing field where the images are processed as high multidimensional matrices to perform various transformations such as blurring, color change, and object detection.

Let’s look at some important Numpy functions that every Data Science aspirant should know but before that:

1. All functions code below assume that the library has been imported with alias np, i.e, import numpy as np.
2. The term “array” will be used to define ndarray after this point.

Check out our data science certifications to upskill yourself

## Different Ways to Initialize

### 1. Linearly Spaced

This function is intended to provide a linear spaced array within the range of values. The function np.linspace(start, stop, num) where the start and stop define the range of values and num define the number of samples, returns evenly spaced values whereas np.arange(start, stop, step) returns values that differ by step values.

### 2. Particular Values

In many instances, you may want to initialize a large matrix with values such as ones, zeros, identity, or constant values. The size of the array is passed as a tuple. Numpy facilitates this via different functions:

• np.zeros(size): Elements are zero
• np.ones(size): Elements are ones
• np.full(size, constant value): Elements are constant value passed.
• np.eye(size): Diagonal elements are ones and the rest are zero. This is the identity matrix.
• np.empty(size): Empty matrix
• np.random.random(size): Random values matrix is initialized of the specified size.

## Ndarray Operations

The main purpose of this library is efficient calculations between different arrays. Numpy supports almost all types of mathematical operations and manipulations that are applied element-wise. Some of them are listed below (Assume two arrays A and B of the same size are initialized with random values):

### 1. Mathematical

• np.subtract(A, B): Subtraction
• np.divide(A, B): Division
• np.multiply(A, B): Multiplication
• np.exp(A): Exponential values
• np.sqrt(A): Square Root values
• np.sin(A), cos(A), tan(A): Trigonometric values
• np.log(A): Logarithmic values
• np.percentile(A, percentile needed, axis): On passing the percentile value, for example, 50, the function will return the 50th percentile of the array.
• A.dot(B): Returns dot product of the arrays
• A == B: Element wise comparison
• np.array_equal(A, B): Array wise comparison
• A.sum(): Sum of all elements
• A.min(), max(): Minimum and Maximum values
• A.cumsum(): Cumulative Sum of elements of the array
• A.corrcoef(): Correlation coefficient

### 2. Manipulations

• np.transpose(A) or A.T: Transpose of the matrix
• A.ravel(): Flattens the array
• A.reshape(new_shape): reshapes the array (here pass the size directly without putting it in the tuple). The new size should be the same as
• A.resize(size): changes the shape of the array into any shape and discards other elements that are not part of this new shape.
• np.concatenate((A,B), axis=1 or 0)
• np.vstack((A,B)): Stack the arrays vertically (row-wise)
• np.hstack((A,B)): Horizontal stack

Check Out: Numpy vs Panda: Difference Between

upGrad’s Exclusive Data Science Webinar for you –

## Explore our Popular Data Science Online Certifications

 Executive Post Graduate Programme in Data Science from IIITB Professional Certificate Program in Data Science for Business Decision Making Master of Science in Data Science from University of Arizona Advanced Certificate Programme in Data Science from IIITB Professional Certificate Program in Data Science and Business Analytics from University of Maryland Data Science Online Certifications

## Miscellaneous Functions

• np.where(): This is an essential function that eliminates the need for if-else statements. It takes 3 important arguments: condition, the value if the condition is satisfied, and the value if not. A simple example of this can be when you have to binarise a column based on a given threshold.
• np.intersect1d(): This function returns the intersection of two 1-d arrays. This means that the common values of these arrays are returned by this function. If the arrays passed are not 1-d then it is flattened.

## Top Data Science Skills You Should Learn

 SL. No Top Data Science Skills to Learn 1 Data Analysis Online Certification Inferential Statistics Online Certification 2 Hypothesis Testing Online Certification Logistic Regression Online Certification 3 Linear Regression Certification Linear Algebra for Analysis Online Certification

• np.allclose(): It is an interesting function. There are situations where you can afford some level of tolerance while comparing arrays or you want to discover similar arrays. This function takes in the arrays and the tolerance value you want. For instance:
• arr1 = np.array([1,2,3,4])
• arr2 = np.array([2,3,4,5])
• np.allclose(arr1, arr2, 0.5) : will return False
• np.allclose(arr1, arr2, 1): will return True
• argmin(), argmax(), and argsort(): As the name suggests, these functions return the indices of the respective names. A.argmin() returns the minimum element index, A.argmax() the opposite, and A.argsort() returns the indices of the sorted array. These functions can come in handy where the result depends on the index.
• np.clip(): This is used to convert the values within a specific range. For instance, if an array has values from 1 to 30 and you want the values between 14 to 27 without losing other values, this function will scale up the values less than 19 to 19 and scale down values greater than 27 to 27.

## Read our popular Data Science Articles

 Data Science Career Path: A Comprehensive Career Guide Data Science Career Growth: The Future of Work is here Why is Data Science Important? 8 Ways Data Science Brings Value to the Business Relevance of Data Science for Managers The Ultimate Data Science Cheat Sheet Every Data Scientists Should Have Top 6 Reasons Why You Should Become a Data Scientist A Day in the Life of Data Scientist: What do they do? Myth Busted: Data Science doesn’t need Coding Business Intelligence vs Data Science: What are the differences?

## Conclusion

There are many more functions while operating on numpy arrays, but these are the most used functions. The operations applied on Pandas columns or series are actually on ndarray as the series is one-dimensional ndarray.

Numpy is a great tool for generating fake Data for testing out specific algorithms or simulating a scenario. It is extensively used in computer vision applications where the image is transformed into multidimensional matrices to perform the required operations or in deep learning where the neural network weights are held by these ndarrays.

If you are curious to learn about data science, check out IIIT-B & upGrad’s PG Diploma in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

#### Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.
Get Free Consultation

Select
Select Area of interest
Select Work Experience
By clicking 'Submit' you Agree to

## Suggested Blogs

101486
Why data mining techniques are important like never before? Businesses these days are collecting data at a very striking rate. The sources of this eno

07 Jul 2024

142255
Association Rule Mining in data mining, as the name suggests, involves discovering relationships between seemingly independent relational databases or

07 Jul 2024

16859
Introduction to Data Mining In its raw form, data requires efficient processing to transform into valuable information. Predicting outcomes hinges on

04 Jul 2024

82617
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes

04 Jul 2024

10082
Introduction Data structures are one of the most fundamental concepts in object-oriented programming. To explain it simply, a data structure is a par

03 Jul 2024

70153
Summary: In this article, you will learn, Difference between Data Science and Data Analytics Job roles Skills Career perspectives Which one is right

02 Jul 2024

51862
In my experience with Data Science, I’ve found that choosing the right data structure is crucial for organizing information effectively. Graphs

01 Jul 2024

14931
The banking sector has many applications for programming and IT solutions. If you’re interested in working on a project for the banking sector,