VOOZH about

URL: https://www.analyticsvidhya.com/blog/2021/07/numpy-a-hands-on-for-beginners/

⇱ Numpy :A Hands On Guide For Beginners - Analytics Vidhya


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

Numpy :A Hands On Guide For Beginners

KAVITA Last Updated : 15 Jul, 2021
5 min read

This article was published as a part of the Data Science Blogathon

What is NumPy and Why NumPy is an important library to work with data?

NumPy is a Python library widely used to handle arrays with arrays. Numpy can handle oversized, multi-dimensional arrays and matrices, along with a large collection of mathematical operations to operate on these arrays. It stands for numerical python. NumPy can provide an array object that is  50 times faster than traditional Python lists.

An array occupies less memory and is extremely convenient to use as compared to python lists.  Additionally, it has a mechanism for specifying the data types. NumPy can operate on individual elements in the array without using loops and list comprehensions.

Now, before diving deep into the concept of NumPy arrays, it’s important to note that Python lists can very well perform all the actions that NumPy arrays perform; it is simply the fact that NumPy arrays are faster and more convenient that lists when it comes extensive computations, which make them extremely useful, especially when you are working with a large amount of data.

Installing NumPy in your System

$ pip install numpy

Getting started with NumPy

Once Numpy is successfully installed in your system, you can import NumPy simply by

import numpy as np

where np is an alias used for NumPy so that the NumPy package can be referred to as np instead of numpy.

There are two ways to create NumPy arrays, which are mentioned below:

  1. By converting the existing lists or tuples to arrays using np.array
  2. By initializing fixed-length arrays using the Numpy functions.
#Creating a 1D numpy array
arr = np.array([1,2,3,4,5])
#Creating a 2D array
arr = np.array( [  [1,2,3],
                   [4,5,6] ] )
# Creating array of ones
np.ones(5) #1D 
np.ones( (3,5) ) #2D
# Change the default dtype of an array 
np.ones( (5) ,dtype = np.int) # creating array of integers
np.ones( (5) ,dtype = np.float ) # creating array of floats
# Creating array of random numbers
np.random.random( [3,4] ) 
#creating an array of numbers 1 to 100 with step of 5
np.arange(1,100,5)
#Creating an array of length 25 between 1 to 10
np.linspace(1,10,25)  # It equally divides 1 to 100 in 25 parts
#creating a array of particular number
np.full( ( 3,3) , 5) #It will create an array of 3x3 of 5's
# To create an array of repeating sequence
np.tile( [1,2,3] , 3 ) # The op will look like [ 1,2,3,1,2,3,1,2,3 ]
# Creating an array of identity matrix
np.eye(3, dtype = int )   # it will create an 3x3 identity matrix
#create a matrix of random integer between a particular range
np.random.randint(0, 10, (3,3))  #3x3 array of random integers ranging from 0 to 9
# creating uninitialized array of specific shape and dtype
np.empty( [3,3] , dtype = int ) 
#create an array of specific shape filled with zeroes
np.zeros( [3,3] , dtype = int )
# Checking shape of an array
arr = np.array( [1,2,3] )
arr.shape
#checking dimensions of an array
arr.ndim
#checking shape of an array
arr.size
#checking the dtype of an array
np.dtype

Reshaping the NumPy arrays

arr = np.array( [1,2,3,4,5,6,7,8,9] ) 
arr.reshape( [3,3]) # convering above array in 3x3 matrix
#flatenning the array
y = np.array( [[1,1], [1,1] ])
y.flatten() # output : [1,1,1,1]

Array Indexing

array_1d[2] # Third element 
array_1d[2:] # Third element onwards 
array_1d[:3] # First three elements 
array_1d[2:7] # Third to seventh elements 
array_1d[0::2] # Subset starting 0 at increment of 2
print(arr[0]) #it will print first row 
print(arr[1]) #it will print second row 
print(arr[0][1]) #it will print second element of first row 
arr=np.array([[81,19,46,74,94],[69,79,26,7,29],[21,45,12,80,72] ])
print(arr[2][1]) #it will print second element of third

Array Slicing

arr=np.array([0,1,2,3,4,5,6,7,8,9,10]) 
print(arr[:5]) #by default its startindex start from [0 1 2 3 4]
print(arr[5:]) #by default its stopindex go till la [ 5 6 7 8 9 10]
print(arr[4:10:2]) #output : [4 6 8]
print(arr[::]) #by default it startindex is 0 stopin [ 1 2 3 4 5 6 7 8 9 10]
arr=np.array([[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18]]) 
print(arr[0,1:5]) #it select first row and element from 1 
#output : [2 3 4 5]
print(arr[1:4,2:4]) #it select row from first to third and 
# output : [[ 9 10] [15 16]]

Concatenation

Concatenate() function can join the sequence of arrays that we provide, along with the axis specified. If the axis is not explicitly given, it is taken as 0

#Concatenating 1D array
arr1=np.array([1,2,3])
arr2=np.array([4,5,6])
arr=np.concatenate((arr1,arr2),axis=0)
print(arr)
#output : [1 2 3 4 5 6]
#Concatenating @d array along axis 0
arr1=np.array([[1,1,1],[1,1,1]])
arr2=np.array([[9,9,9,],[9,9,9]])
arr=np.concatenate((arr1,arr2),axis=0)
print(arr)
 #output : [[1 1 1]
 [1 1 1]
 [9 9 9]
 [9 9 9]]
#concatenating along axsi 1
arr1=np.array([[1,1,1],[1,1,1]]) 
arr2=np.array([[9,9,9,],[9,9,9]]) 
arr=np.concatenate((arr1,arr2),axis=1) 
print(arr) 
#output : [[1 1 1 9 9 9] 
 [1 1 1 9 9 9]]

Joining array using Stack function

Stacking is the same as concatenation, the only difference is that stacking is done along a new axis.

#stacking two 1D arrays horizontally
arr1=np.array([0,0]) 
arr2=np.array([1,1])
arr=np.hstack((arr1,arr2))
# Stacking two 2D arrays horizontally
arr1=np.array([[0,0],[0,0]]) 
arr2=np.array([[1,1],[1,1]]) 
arr=np.hstack((arr1,arr2)) 
print(arr)
output : [[0 0 1 1] 
 [0 0 1 1]]

#Stacking 1D arrays vertically
arr1=np.array([0,0]) 
arr2=np.array([1,1]) 
arr=np.vstack((arr1,arr2)) 
print(arr) 
#output :[[0 0] 
 [1 1]]
# Stacking 2D arrays vertically
arr1=np.array([[0,0],[0,0]]) 
arr2=np.array([[1,1],[1,1]]) 
arr=np.vstack((arr1,arr2)) 
print(arr) 
#output : [[0 0] 
 [0 0] 
 [1 1] 
 [1 1]]

Sort the arrays

sorting means simply arranging elements in an ordered sequence.

arr=np.array([3,2,0,1]) 
print(np.sort(arr)) 
#output : [0 1 2 3]

Operations on  Arrays

array_1 + array_2

np.array([0,1]) + np.array([2,3])

array_1 – array_2

np.array([0,1]) + np.array([2,3])

array_1 * array_2

np.array([0,1]) * np.array([2,3])

some_array ** n  , where n is any real number

np.array([0,1])**2 #squaring
np.array([1,2]) ** 1.2 #raising power by 1.2

NumPy provides the functions sin(), cos() and tan()

np.sin(some_array)

np.cos(some_array)

np.tan(some_array)

arr = np.array([1,2,3])
print( np.sin(arr) )
print( np.cos(arr) )
print( np.tan(arr) )

np.exp(some_array)

np.exp(arr)

np.log(some_array)

np.log( arr )
A = np.array([[6, 1, 1],
[4, -2, 5],
[2, 8, 7]])
# Rank of a matrix
print( np.linalg.matrix_rank(A) )
# Trace of matrix A
print( np.trace(A) )
# Determinant of a matrix
print(np.linalg.det(A) )
# Inverse of matrix A
print( np.linalg.inv(A) )
#raising power of each elt in matrix
print(np.linalg.matrix_power(A, 3))

eigen_val, eigen_vec = np.linalg.eig(some_array) # to find eigen value and eigen vectors

End Notes

Thanks for reading!

We did some hands-on NumPy.I hope you enjoyed the article.

Image source links :

Image1:https://cdn.educba.com/academy/wp-content/uploads/2019/04/What-is-NumPy-1.jpg.webp

Image 2: https://www.w3resource.com/w3r_images/numpy-manipulation-concatenate-function-image-1.png

Image 3: https://www.w3resource.com/w3r_images/python-numpy-image-exercise-58.png

Image 4: https://www.w3resource.com/w3r_images/numpy-manipulation-hstack-function-image-1.png

Image 5: https://www.w3resource.com/w3r_images/numpy-manipulation-vstack-function-image-1.png

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

A Mathematics student turned Data Scientist. I am an aspiring data scientist who aims at learning all the necessary concepts in Data Science in detail. I am passionate about Data Science knowing data manipulation, data visualization, data analysis, EDA, Machine Learning, etc which will help to find valuable insights from the data.

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
πŸ‘ Av Logo White

Continue your learning for FREE

Forgot your password?
πŸ‘ Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

πŸ‘ Popup Banner
πŸ‘ AI Popup Banner