0% found this document useful (0 votes)
7 views16 pages

Python NumPy | GeeksforGeeks

Uploaded by

rohan.cpa1xl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views16 pages

Python NumPy | GeeksforGeeks

Uploaded by

rohan.cpa1xl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Data Science IBM Certification Numpy exercise pandas Matplotlib Data visulisation

Python NumPy
Last Updated : 26 Mar, 2025

Numpy is a general-purpose array-processing package. It provides a high-


performance multidimensional array object, and tools for working with these
arrays. It is the fundamental package for scientific computing with Python.

Besides its obvious scientific uses, Numpy can also be used as an efficient
multi-dimensional container of generic data.

Arrays in Numpy
Array in Numpy is a table of elements (usually numbers), all of the same
type, indexed by a tuple of positive integers. In Numpy, number of
dimensions of the array is called rank of the array. A tuple of integers giving
the size of the array along each dimension is known as shape of the array.
An array class in Numpy is called as ndarray. Elements in Numpy arrays
are accessed by using square brackets and can be initialized by using
nested Python Lists.

Creating a Numpy Array

Arrays in Numpy can be created by multiple ways, with various number of


Ranks, defining the size of the Array. Arrays can also be created with the
use of various data types
Open In such
App as lists, tuples, etc. The type of the resultant
array is deduced from the type of the elements in the sequences.
Note: Type of array can be explicitly defined while creating the array.
:
1 import numpy as np
2
3 # Creating a rank 1 Array
4 arr = np.array([1, 2, 3])
5 print(arr)
6
7 # Creating a rank 2 Array
8 arr = np.array([[1, 2, 3],
9 [4, 5, 6]])
10 print(arr)
11
12 # Creating an array from tuple
13 arr = np.array((1, 3, 2))
14 print(arr)

Output

Array with Rank 1:


[1 2 3]
Array with Rank 2:
[[1 2 3]
[4 5 6]]

Array created using passed tuple:


[1 3 2]

Accessing the array Index

In a numpy array, indexing or accessing the array index can be done in


multiple ways. To print a range of an array, slicing is done. Slicing of an
array is defining a range in a new array which is used to print a range of
elements from the original array. Since, sliced array holds a range of
elements of the original array, modifying content with the help of sliced array
modifies the original array content.
:
1 import numpy as np
2
3 arr = np.array([[-1, 2, 0, 4],
4 [4, -0.5, 6, 0],
5 [2.6, 0, 7, 8],
6 [3, -7, 4, 2.0]])
7
8 # Printing a range of Array
9 # with the use of slicing method
10 arr2 = arr[:2, ::2]
11 print ("first 2 rows and alternate columns(0 and
2):\n", arr2)
12
13 # Printing elements at
14 # specific Indices
15 arr3 = arr[[1, 1, 0, 3],
16 [3, 2, 1, 0]]
17 print ("\nElements at indices (1, 3), "
18 "(1, 2), (0, 1), (3, 0):\n", arr3)

Output

first 2 rows and alternate columns(0 and 2):


[[-1. 0.]
[ 4. 6.]]

Elements at indices (1, 3), (1, 2), (0, 1), (3, 0):
[0. 6. 2. 3.]

Basic Array Operations


:
In numpy, arrays allow a wide range of operations which can be performed
on a particular array or a combination of Arrays. These operation include
some basic Mathematical operation as well as Unary and Binary operations.

1 import numpy as np
2
3 # Defining Array 1
4 a = np.array([[1, 2],
5 [3, 4]])
6
7 # Defining Array 2
8 b = np.array([[4, 3],
9 [2, 1]])
10
11 # Adding 1 to every element
12 print ("Adding 1 to every element:", a + 1)
13
14 # Subtracting 2 from each element
15 print ("\nSubtracting 2 from each element:", b - 2)
16
17 # sum of array elements
18 # Performing Unary operations
19 print ("\nSum of all array elements: ", a.sum())
20
21 # Adding two arrays
22 # Performing Binary operations
23 print ("\nArray sum:\n", a + b)

Output

Adding 1 to every element: [[2 3]


[4 5]]

Subtracting 2 from each element: [[ 2 1]


:
[ 0 -1]]

Sum of all array elements: 10

Array sum:
[[5 5]
[5 5]]

More on Numpy Arrays

Basic Array Operations in Numpy


Advanced Array Operations in Numpy
Basic Slicing and Advanced Indexing in NumPy Python

Data Types in Numpy


Every Numpy array is a table of elements (usually numbers), all of the same
type, indexed by a tuple of positive integers. Every ndarray has an
associated data type (dtype) object. This data type object (dtype) provides
information about the layout of the array. The values of an ndarray are
stored in a buffer which can be thought of as a contiguous block of memory
bytes which can be interpreted by the dtype object. Numpy provides a large
set of numeric datatypes that can be used to construct arrays. At the time of
Array creation, Numpy tries to guess a datatype, but functions that construct
arrays usually also include an optional argument to explicitly specify the
datatype.

Constructing a Datatype Object

In Numpy, datatypes of Arrays need not to be defined unless a specific


datatype is required. Numpy tries to guess the datatype for Arrays which are
not predefined in the constructor function.
:
1 import numpy as np
2
3 # Integer datatype
4 x = np.array([1, 2])
5 print(x.dtype)
6
7 # Float datatype
8 x = np.array([1.0, 2.0])
9 print(x.dtype)
10
11 # Forced Datatype
12 x = np.array([1, 2], dtype = np.int64)
13 print(x.dtype)

Output

int64
float64
int64

Math Operations on DataType array

In Numpy arrays, basic mathematical operations are performed element-


wise on the array. These operations are applied both as operator overloads
and as functions. Many useful functions are provided in Numpy for
performing computations on Arrays such as sum: for addition of Array
elements, T: for Transpose of elements, etc.
:
1 import numpy as np
2
3 # First Array
4 arr1 = np.array([[4, 7], [2, 6]],
5 dtype = np.float64)
6
7 # Second Array
8 arr2 = np.array([[3, 6], [2, 8]],
9 dtype = np.float64)
10
11 # Addition of two Arrays
12 Sum = np.add(arr1, arr2)
13 print(Sum)
14
15 # Addition of all Array elements
16 Sum1 = np.sum(arr1)
17 print(Sum1)
18
19 # Square root of Array
20 Sqrt = np.sqrt(arr1)
21 print(Sqrt)
22
23 # Transpose of Array
24 Trans_arr = arr1.T
25 print(Trans_arr)

Output

Addition of Two Arrays:


[[ 7. 13.]
[ 4. 14.]]

Addition of Array elements:


19.0
:
Square root of Array1 elements:
[[2. 2.64575131]
[1.41421356 2.44948974]]

Transpose of Array:
[[4. 2.]
...

More on Numpy Data Type


Data type Object (dtype) in NumPy

Methods in Numpy:

all() diag() hypot() ones_like()

any() diagflat() absolute() full_like()

take() diag_indices() ceil() sin()

put() asmatrix() floor() cos()

apply_along_axis() bmat() degrees() tan()

apply_over_axes() eye() radians() sinh()

argmin() roll() npv() cosh()

argmax() identity() fv() tanh()

nanargmin() arange() pv() arcsin()


:
nanargmax() place() power() arccos()

amax() extract() float_power() exp()

amin() compress() log() exp2()

insert() rot90() log1() fix()

delete() tile() log2() logical_or()

append() reshape() log10() logical_and()

around() ravel() dot() logical_not()

flip() isinf() vdot() logical_xor()

fliplr() isrealobj() trunc() array_equal()

flipud() isscalar() divide() array_equiv()

triu() isneginf() floor_divide() arctan2()

tril() isposinf() true_divide() equal()

tri() iscomplex() random.rand() not_equal()

empty() isnan() random.randn() less()

empty_like() iscomplexobj() ndarray.flat() less_equal()

zeros() isreal() expm1() greater()

zeros_like() isfinite() bincount() greater_equal()


:
ones() isfortran() rint() prod()

arctan() cbrt() square()

Programs on Numpy

Python | Check whether a list is empty or not


Python | Get unique values from a list
Python | Multiply all numbers in the list (3 different ways)
Transpose a matrix in Single line in Python
Multiplication of two Matrices in Single line using Numpy in Python
Python program to print checkerboard pattern of nxn using numpy
Graph Plotting in Python | Set 1, Set 2, Set 3

Useful Numpy Articles

Matrix manipulation in Python


Basic Slicing and Advanced Indexing in NumPy Python
Differences between Flatten() and Ravel()
rand vs normal in Numpy.random in Python

Advertise with us Next Article

ku… Follow

Article Tags : Numpy Python-numpy


:
Similar Reads

NumPy Array in Python


NumPy (Numerical Python) is a powerful library for numerical
computations in Python. It is commonly referred to multidimensional…
container that holds the same data type. I...
13 min read

numpy.loadtxt() in Python
numpy.loadtxt() function is used to load data from a text file and return
it as a NumPy array. It is ideal for reading large data sets that are…
stored in simple text forma...
15+ min read

numpy.multiply() in Python
The numpy.multiply() is a numpy function in Python which is used to
find element-wise multiplication of two arrays or scalar (single value)…
It returns the product of two...
15+ min read

Python 101
Welcome to "Python 101," your comprehensive guide to
understanding and mastering the fundamentals of Python…
programming. Python is a versatile and powerful high-level prog...
15+ min read

NumPy Tutorial - Python Library


NumPy (short for Numerical Python ) is one of the most fundamental
libraries in Python for scientific computing. It provides support for…
large, multi-dimensional arrays an...
15+ min read

Python for AI
:
Python for AI
Python has become the go-to programming language for artificial
intelligence (AI) development due to its simplicity and the powerful…
suite of libraries it offers. Its synt...
15+ min read

numpy.fromstring() function – Python


numpy.fromstring() function create a new one-dimensional array
initialized from text data in a string. Syntax : numpy.fromstring(string…
dtype = float, count = -1, sep = '...
6 min read

Python: Operations on Numpy Arrays


NumPy is a Python package which means 'Numerical Python'. It is the
library for logical computing, which contains a powerful n-dimension…
array object, gives tools to int...
15+ min read

NLP Libraries in Python


In today's AI-driven world, text analysis is fundamental for extracting
valuable insights from massive volumes of textual data. Whether…
analyzing customer feedback, unders...
15+ min read

Data Analysis with Python


In this article, we will discuss how to do data analysis with Python. We
will discuss all sorts of data analysis i.e. analyzing numerical data wi…
NumPy, Tabular data wit...
15+ min read

Corporate & Communications


:
Corporate & Communications
Address:
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar
Pradesh (201305)

Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida, Gautam
Buddh Nagar, Uttar Pradesh, 201305

Advertise with us

Company
About Us
Legal
Privacy Policy
Careers
In Media
Contact Us
GfG Corporate Solution
Placement Training Program

Explore
Job-A-Thon Hiring Challenge
GfG Weekly Contest
Offline Classroom Program
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos

Languages
Python
Java
C++
PHP
GoLang
SQL
:
R Language
Android Tutorial

DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming

Data Science & ML


Data Science With Python
Data Science For Beginner
Machine Learning
ML Maths
Data Visualisation
Pandas
NumPy
NLP
Deep Learning

Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS

Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question

Computer Science
:
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths

DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap

System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions

School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar

Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
:
Preparation Corner
Company-Wise Recruitment Process
Aptitude Preparation
Puzzles
Company-Wise Preparation

More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets

Machine Learning/Data Science


Complete Machine Learning & Data Science Program - [LIVE]
Data Analytics Training using Excel, SQL, Python & PowerBI - [LIVE]
Data Science Training Program - [LIVE]
Data Science Course with IBM Certification

Programming Languages
C Programming with Data Structures
C++ Programming Course
Java Programming Course
Python Full Course

Clouds/Devops
DevOps Engineering
AWS Solutions Architect Certification
Salesforce Certified Administrator Course

GATE 2026
GATE CS Rank Booster
GATE DA Rank Booster
GATE CS & IT Course - 2026
GATE DA Course 2026
GATE Rank Predictor

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


:

You might also like