0% found this document useful (0 votes)
12 views

NumPy

NumPy is an open-source Python library essential for numerical data processing in various scientific and engineering fields, providing efficient array and matrix operations. It features the ndarray object, which allows for fast computations and supports a wide range of mathematical functions, making it a preferred choice for data scientists. NumPy's advantages include faster performance than traditional Python lists, ease of use, and compatibility with other data science libraries like SciPy and Pandas.

Uploaded by

Anjali Negi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

NumPy

NumPy is an open-source Python library essential for numerical data processing in various scientific and engineering fields, providing efficient array and matrix operations. It features the ndarray object, which allows for fast computations and supports a wide range of mathematical functions, making it a preferred choice for data scientists. NumPy's advantages include faster performance than traditional Python lists, ease of use, and compatibility with other data science libraries like SciPy and Pandas.

Uploaded by

Anjali Negi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Introduction

NumPy stands for Numerical Python.

NumPy is an open source Python library that’s used in almost every field
of science and engineering. It’s the universal standard for working with
numerical data in Python, and it’s at the core of the scientific Python and
PyData ecosystems. NumPy users include everyone from beginning coders to
experienced researchers doing state-of-the-art scientific and industrial
research and development.

NumPy was created in 2005 by Travis Oliphant. It is an open source


project and you can use it freely.

The NumPy API is used extensively in Pandas, SciPy, Matplotlib, scikit-learn,


scikit-image and most other data science and scientific Python packages.

The NumPy library contains multidimensional array and matrix data


structures. It provides ndarray, a homogeneous n-dimensional array object,
with methods to efficiently operate on it. NumPy can be used to perform
a wide variety of mathematical operations on arrays. It adds powerful
data structures to Python that guarantee efficient calculations with arrays
and matrices and it supplies an enormous library of high-level mathematical
functions that operate on these arrays and matrices.

NumPy is a Python library and is written partially in Python, but


most of the parts that require fast computation are written in C or
C++.

Importance of NumPy

With the revolution of data science, data analysis libraries like NumPy, SciPy,
Pandas, etc. have seen a lot of growth. With a much easier syntax than
other programming languages, python is the first choice language for the
data scientist.

NumPy aims to provide an array object that is up to 50x faster than


traditional Python lists.

The array object in NumPy is called ndarray, it provides a lot of


supporting functions that make working with ndarray very easy.

Arrays are very frequently used in data science, where speed and resources
are very important.

NumPy provides a convenient and efficient way to handle the vast


amount of data. NumPy is also very convenient with Matrix
multiplication and data reshaping. NumPy is fast which makes it
reasonable to work with a large set of data.
There are the following advantages of using NumPy for data analysis.

1. NumPy performs array-oriented computing.


2. It efficiently implements the multidimensional arrays.
3. It performs scientific computations.
4. It is capable of performing Fourier Transform and reshaping the data
stored in multidimensional arrays.
5. NumPy provides the in-built functions for linear algebra and random
number generation.

Nowadays, NumPy in combination with SciPy and Mat-plotlib is used as the


replacement to MATLAB as Python is more complete and easier
programming language than MATLAB.

NumPy is Faster than Lists

NumPy arrays are stored at one continuous place in memory unlike


lists, so processes can access and manipulate them very efficiently.

This behavior is called locality of reference in computer science.

This is the main reason why NumPy is faster than lists. Also it is optimized to
work with latest CPU architectures.

Installation of NumPy

If you have Python and PIP already installed on a system, then installation of
NumPy is very easy.

Install it using this command:

C:\Users\Your Name>pip install numpy

Note: PIP is a package manager for Python packages, or modules if you like
Import NumPy

Once NumPy is installed, import it in your applications by adding


the import keyword:

import numpy

Check if PIP is Installed

Navigate your command line to the location of Python's script directory, and
type the following:

Example:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\
Scripts>pip --version

Install PIP

If you do not have PIP installed, you can download and install it from this
page: https://pypi.org/project/pip/

Array

An array is a central data structure of the NumPy library. It has a grid


of elements that can be indexed. The elements are all of the same type,
referred to as the array dtype.

An array can be indexed by a tuple of nonnegative integers, by booleans, by


another array, or by integers. The rank of the array is the number of
dimensions. The shape of the array is a tuple of integers giving the size of
the array along each dimension.

An array referred to as a “ndarray,” which is shorthand for “N-


dimensional array.” An N-dimensional array is simply an array with
any number of dimensions. You might also hear 1-D, or one-dimensional
array, 2-D, or two-dimensional array, and so on. The NumPy ndarray class is
used to represent both matrices and vectors. A vector is an array with a
single dimension (there’s no difference between row and column vectors),
while a matrix refers to an array with two dimensions. For 3-D or higher
dimensional arrays, the term tensor is also commonly used.

Example 1:

import numpy

ar = numpy.array([1, 2, 3, 4, 5])

print(ar)

Output:

[1 2 3 4 5]

Example 2:

import numpy as np

ar = np.array([1, 2, 3, 4, 5])

print(ar)

print(type(ar))

Output:

[1 2 3 4 5]
<class 'numpy.ndarray'>

Example 3:

# we can pass a list, tuple or any array-like object into the array() method,
and it will be converted into an ndarray(N-dimensional array)

import numpy as np

ar1=np.array((1, 2, 3, 4, 5))

ar2=np.array([11,22,33,44,55])

print(ar1)

print(ar2)

Output:

[1 2 3 4 5]

[11 22 33 44 55]

Note: To check version on NumPy write:

import numpy as np

print(np.__version__)

Output:

1.19.5

Dimensions in Arrays

A dimension in arrays is one level of array depth (nested arrays).

NumPy has a whole sub module dedicated towards matrix operations


called numpy.mat

0-D Arrays/ 0 Dimensional Array

0-D arrays, or Scalars, are the elements in an array. Each value in an array is
a 0-D array.

Example:

import numpy as np

arr = np.array(10)

print(arr)
Output:

10

1-D Arrays/1 Dimensional Array

An array that has 0-D arrays as its elements is called uni-dimensional or 1-D
array.

These are the most common and basic arrays.

Example:

import numpy as np

arr = np.array([10, 20, 30, 40, 50])

print(arr)

Output:

[10 20 30 40 50]

2-D Arrays/2 Dimesional Array

An array that has 1-D arrays as its elements is called a 2-D array.

These are often used to represent matrix or 2nd order tensors.

Example:
import numpy as np

arr = np.array([[10, 20, 30],[40, 50, 60]])


print(arr)

Output:

[[10 20 30]

[40 50 60]]

3-D arrays/3 Dimensional Array

An array that has 2-D arrays (matrices) as its elements is called 3-D array.

These are often used to represent a 3rd order tensor.

OR

Example:

import numpy as np

ar = np.array([[[10, 20, 30], [40, 50, 60]], [[11, 22, 33], [44, 55, 66]]])

print(ar)

Output:

[[[10 20 30]

[40 50 60]]
[[11 22 33]

[44 55 66]]]

Check Number of Dimensions

NumPy Arrays provides the ndim attribute that returns an integer that tells
us how many dimensions the array have.

Example:

import numpy as np

a = np.array(42)

b = np.array([10, 20, 30, 40, 50])

c = np.array([[10, 20, 30], [40, 50, 60]])

d = np.array([[[10, 20, 30], [40, 50, 60]], [[11, 22, 33], [44, 55, 66]]])

print("Dimesion of Array= ",a.ndim)

print("Dimesion of Array= ",b.ndim)

print("Dimesion of Array= ",c.ndim)

print("Dimesion of Array= ",d.ndim)

Output:

Dimesion of Array= 0

Dimesion of Array= 1

Dimesion of Array= 2

Dimesion of Array= 3

Array Indexing - Accessing Array elements

After creating array with different elements, we can access any element from
the array. Elements of elements can be accessed in different way.

Example 1:

#accessing one element from 1D Array


import numpy as np

arr = np.array([10, 20, 30, 40])

print(arr[1])

Output:

20

Example 2:

#accessing one element from 2D Array

import numpy as np

arr = np.array([[10,20,30,40], [50,60,70,80]])

print(arr[0, 2])

Output:

30

Example 3:

import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

print(arr[0, 1, 2])

Output:

shape()

This method is used to find shape(dimension) of array in numpy.

Example:

import numpy as np

ar = np.array([[1, 2, 3], [4, 5,6]])

print(ar.shape)

Output:

(2, 3)

reshape()
This method is used to give a new shape to array. With this method we can
divide array elements into different rows and columns. The point which is to
be noted here is that data in the array will not be changed, it will be
restructured.

Note: While using the reshape method, the array you want to produce needs
to have the same number of elements as the original array.

Example 1:

# Can create array using arrange where elements are added in array in
countinuity

import numpy as np

a = np.arange(10)

print(a)

Output:

[0 1 2 3 4 5 6 7 8 9]

Example 2:

#Convert 1 D array into 2 D array with 3 rows and 2 columns.

import numpy as np

a = np.arange(6)

b = a.reshape(3, 2)

print(b)

Output:

[[0 1]

[2 3]

[4 5]]

Example 3:

import numpy as np

a = np.arange(10)
b = a.reshape(3, 2)

print(b)

Output:

Error

Cannot reshape array of size 10 into shape (3,2)

Example 4:
#Converting 2D into 1D Array
import numpy as np
ar1 = np.array([[10, 20, 30], [40, 50, 60]])
print("Original array \n",ar1)
ar2=ar1.reshape(-1)
print("\n New Array\n",ar2)

Output:
Original array
[[10 20 30]
[40 50 60]]
New Array[10 20 30 40 50 60]

Example 5:

#Converting 1D into 3D array

import numpy as np

ar1 = np.array([10,20,30,40,50,60,70,80,90,100,110,120])

print("Original array \n",ar1)

ar2=ar1.reshape(2,2,3)

print("\n New Array\n",ar2)

Output:

Original array

[ 10 20 30 40 50 60 70 80 90 100 110 120]


New Array

[[[ 10 20 30]

[ 40 50 60]]

[[ 70 80 90]

[100 110 120]]]

Element Wise Operations

Apart from creating and reshaping we can also perform certain


operations on arrays. NumPy array supports different types of operators
that allow you to easily process the values of these arrays.

Arithmetic operators and functions

The arithmetic operations like addition, subtraction, multiplication and


division are possible on numpy arrays.

The good thing here is:

 There is no need to use loops


 No special operator is required to perform above mentioned
operators.
 New array can be created after performing any arithmetic
operation

Example 1:

import numpy as np

ar1 = np.array([1,2,3])

ar2 = np.array([4,5,6])

ar3=ar1+ar2

print(ar3)

Output:

[5 7 9]
Example 2:

import numpy as np

ar1 = np.array([1,2,3])

ar2 = np.array([4,5,6])

ar3=ar1-ar2

print(ar3)

Output:

[-3 -3 -3]

Example 3:

import numpy as np

ar1 = np.array([1,2,3])

ar2 = np.array([4,5,6])

ar3=ar1*ar2

print(ar3)

Output:

[4 10 18]

Example 4:

import numpy as np

ar1 = np.array([6,2,8])

ar2 = np.array([2,1,4])

ar3=ar1/ar2

print(ar3)

Output:

[3. 2. 2.]

Example 5:

import numpy as np

ar1 = np.array([6,2,8,12])

ar2 = np.array([2,1,4])
ar3=ar1+ar2

print(ar3)

Output:

Error

operands could not be broadcast together with shapes (4,) (3,)

Example 6:

import numpy as np

ar1 = np.array([1,2,3,4,5])

ar1 = ar1+10

print(ar1)

Output:

[11 12 13 14 15]

Example 7:

import numpy as np

ar=np.array([1,2,3,4,5])

print(np.power(ar, 2))

Output:

[ 1 4 9 16 25]

Example 8:

import numpy as np

ar=np.array([1.6,2.3,3.3,4.8,5.2])

print(np.floor(ar))

print(np.ceil(ar))

print(np.round(ar))

Output:

[1. 2. 3. 4. 5.]

[2. 3. 4. 5. 6.]
[2. 2. 3. 5. 5.]

Example 9:

import numpy as np

ar=np.array([1,2,3,4,5])

print(ar**2)

Output:

[ 1 4 9 16 25]

Comparison Operations

Elements of array can be compared using all relational operators.

Example 1:

import numpy as np

a = np.array([3, 8, 3, 4])

b = np.array([4, 8, 4, 4])

print(a==b)

Output:

[False True False True]

Example 2:

import numpy as np

a = np.array([3, 8, 3, 4])

b = np.array([4, 2, 4, 1])

print(a>b)

Output:

[False True False True]

Logical Operations

NumPy array also supports all the logical operators that allow you to
easily compare the array element.

Example:

import numpy as np
ar=np.array([1,2,3,4,5])

print(ar)

print("Is any element greater than 3--> ",np.any(ar>3))

print("Are all elements greater than 3--> ",np.all(ar>3))

Output:

[1 2 3 4 5]

Is any element greater than 3--> True

Are all elements greater than 3--> False

Aggregate functions

Numpy has fast built-in aggregate and statistical for working on arrays.

With the help of aggregate functions we perform various operations like


finding minimum, maximum element etc.

Some of the aggregate functions are:

1. np.sum(m): Used to find out the sum of the given array.


2. np.prod(m): Used to find out the product(multiplication) of the values of m.
3. np.mean(m): It returns the mean of the input array m.
4. np.std(m): It returns the standard deviation of the given input array m.
5. np.var(m): Used to find out the variance of the data given in the form of array m.
6. np.min(m): It returns the minimum value among the elements of the given array m.
7. np.max(m): It returns the maximum value among the elements of the given array
0m.
8. np.argmin(m): It returns the index of the minimum value among the elements of
the array m.
9. np.argmax(m): It returns the index of the maximum value among the elements of
the array m.

Example 1:

import numpy as np

ar=np.array([1,2,3,4,5,5,4,3,2,1])

print(ar)

print("Sum of elements= ",ar.sum())


print("Product of elements= ",ar.prod())

print("Mean of elements= ",ar.mean())

print("Standard deviation of elements= ",ar.std())

print("Variance of elements= ",ar.var())

print("Minimum element= ",min(ar))

print("Index of minimum element= ",ar.argmin())

print("Maximum element= ",max(ar))

print("Index of maximum value= ",ar.argmax())

Output:

[1 2 3 4 5 5 4 3 2 1]

Sum of elements= 30

Product of elements= 14400

Mean of elements= 3.0

Standard deviation of elements= 1.4142135623730951

Variance of elements= 2.0

Minimum element= 1

Index of minimum element= 0

Maximum element= 5

Index of maximum value= 4

Slicing arrays

Slicing in python means taking elements from one given index to another
given index.

We pass slice instead of index like this: [start:end].

We can also define the step, like this: [start:end:step]

Example 1:

import numpy as np

ar = np.array([1, 2, 3, 4, 5])

print(ar[0:5])
print(ar[2:5])

print(ar[0:])

print(ar[:5])

print(ar[-4:-1])

print(ar[0:5:2])

Output:

[1 2 3 4 5]

[3 4 5]

[1 2 3 4 5]

[1 2 3 4 5]

[2 3 4]

[1 3 5]

Example 2:

import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(arr[0, 1:4])

print(arr[1, 2:5])

print("\n")

Output:

[2 3 4]

[ 8 9 10]

Example 3:

import numpy as np

import numpy as np

ar = np.array([[[10, 20, 30], [40, 50, 60]], [[11, 22, 33], [44, 55, 66]]])

print(ar)

print("\n\n")
print("\n",ar[0,0,1:2])

print("\n",ar[1,0,1:3])

Output:

[[[10 20 30]

[40 50 60]]

[[11 22 33]

[44 55 66]]]

[20]

[22 33]

Adding Row/Column to array

Numpy module in python, provides a function numpy.append() to append


objects to the end of an array,

append()

Numpy module in python, provides a function numpy.append() to append


objects to the end of an array, The object should be an array like entity. The
append() method will take an array, object to be appended as arguments. It
returns a copy of the numpy array, with given values appended at the end.

Syntax:

numpy.append(arr, values, axis=None)

where,

arr = The array to be passed to the function.


values = array_like object to appended to the array.
axis = int, optional, Axis along which to append values. If not provided, the
array is flattened before appending.
Example 1: #adding elements in 1D array

import numpy as np

# Creating an initial array

arr = np.array([1, 2, 3])

# Appending a value to the end

new_arr = np.append(arr, 4)

print("Original array:", arr)

print("New array after appending:", new_arr)

Output:

Original array: [1 2 3]

New array after appending: [1 2 3 4]

Example 2:

# add row using append() method

import numpy as np

ar = np.array([[1, 2, 3, 4, 5],

[5, 4, 3, 2, 1]])

row = np.array([6, 7, 8, 9, 1])

ar = np.append(ar, [row],axis=0)

print(ar)

Output:

[[1 2 3 4 5]

[5 4 3 2 1]

[6 7 8 9 1]]

Example 3:

# add column using append() method

import numpy as np
ar = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(ar);

col = np.array([[10], [11], [12]])

ar = np.append(ar, col, axis=1)

print ("After adding column: \n", ar)

Output:

[[1 2 3]

[4 5 6]

[7 8 9]]

After adding column:

[[ 1 2 3 10]

[ 4 5 6 11]

[ 7 8 9 12]]

insert() method

Numpy module in python, provides a function numpy.insert() to insert values


along the given axis before the given index. The insert() method will take an
array, index , values to be inserted as parameters. It will insert the given
value just before the specified index and returns the array.

Now, to Add a Row to a NumPy Array we need to pass the array, index, row
to be inserted to the insert() method. Here we are adding row at front of the
array so let’s give index = 0.

Syntax of insert()

numpy.insert(arr, obj, values, axis=None)

where,

arr = The array to be passed to the function.

obj = index at which value needs to be inserted

values = Values or object to insert into array.

axis = int, optional, Axis along which to insert values.


Example 1:

#adding row using insert method

import numpy as np

ar = np.array([[1, 2, 3, 4, 5],

[6, 7, 8, 9, 10]])

row = np.array([2, 4, 6, 8, 1])

ar = np.insert(ar, 0, row, axis=0)

print(ar)

Output:

[[ 2 4 6 8 1]

[ 1 2 3 4 5]

[ 6 7 8 9 10]]

Example 2:

#adding column using insert() method

import numpy as np

ar = np.array([[1, 2, 3, 4, 5],

[6, 7, 8, 9, 10]])

col = np.array([[2, 4]])

ar = np.insert(ar, 5, col, axis=1)

print(ar)

Output:

[[ 1 2 3 4 5 2]

[ 6 7 8 9 10 4]]

vstack() and hstack()method

Numpy module in python, provides a function numpy.vstack() function is


used to Stack arrays in sequence vertically and horizontally. The vstack()
method will take a sequence of arrays as parameters. It will stack the arrays
into one single array and returns the array. The vstack is equivalent to
concatenation.
Now to Add a Row to a NumPy Array, In the sequence of arrays we will pass
the given array and the row to be added, The vstack() method will return the
array with the row added.

Syntax:

numpy.vstack(tuple)

where,

tuple = sequence of arrays to be passed to the function

Example:

# adding row using vstack() method

import numpy as np

ar = np.array([[1, 2, 3, 4, 5],

[5, 4, 3, 2, 1]])

row = np.array([6,7,8,9,1])

ar = np.vstack((ar,row))

print(ar)

Output:

[[1 2 3 4 5]

[5 4 3 2 1]

[6 7 8 9 1]]

Example 2:

#adding columns using hstack() method

import numpy as np

ar = np.array([[1, 2, 3, 4, 5],

[5, 4, 3, 2, 1]])

col = np.array([[66],[55]])

ar = np.hstack((ar,col))
print(ar)

Output:

[[ 1 2 3 4 5 66]

[ 5 4 3 2 1 55]]

Array Manipulation

Several routines are available in NumPy package for manipulation of


elements in ndarray object. This topic present the functions of Basic
operations, Changing array shape, Transpose-like operations, Changing
number of dimensions, Changing kind of array, Joining arrays, Splitting
arrays, Tiling arrays, Adding and removing elements and Rearranging
elements to access data and subarrays, and to split, reshape, and join the
arrays.

reshape() - this method is used to reshape the elements of array with


different dimensions.

Example:

#Convert 1 D array into 2 D array with 3 rows and 2 columns.

import numpy as np

a = np.arange(6)

b = a.reshape(3, 2)

print(b)

Output:

[[0 1]

[2 3]

[4 5]]

flat()- this method returns element corresponding to index in flattened


array.

 Returns an Iterator: The flat attribute returns an iterator, not a copy


of the array. It provides a way to iterate over the elements of the array
as if it were a 1-dimensional array.

 Attribute of an Array Object: It is an attribute of an array object,


not a method.
Example:

import numpy as np

ar = np.array([[1, 2, 3, 4, 5],

[5, 4, 3, 2, 1]])

print("The original array: ")

print(ar)

print("\n")

print(ar.flat[6])

Output:

The original array:

[[1 2 3 4 5]

[5 4 3 2 1]]

flatten()-this method is used to flatten array elements.

 Returns a Copy: The flatten() method returns a new 1-dimensional


array, which is a copy of the original array. Any modifications made to
the flattened array do not affect the original array.

 Method of an Array Object: It is a method that can be called directly


on an array object.

Example:

import numpy as np

ar = np.array([[1, 2, 3, 4, 5],

[5, 4, 3, 2, 1]])

print("The original array is:")

print(ar)

print("\n")

print("The flattened array is:")


print(ar.flatten())

Output:

The original array is:

[[1 2 3 4 5]

[5 4 3 2 1]]

The flattened array is:

[1 5 2 4 3 3 4 2 5 1]

Note:

print(ar.flatten(order='F')) : flatten column wise (default)

print(ar.flatten(order='A')) : flatten row wise

print(ar.flatten(order='K')) : according to sequence in which they appear in


memory.

ravel()-this method is used to flatten array elements.

Example:

import numpy as np

ar = np.array([[1, 2, 3, 4, 5],

[5, 4, 3, 2, 1]])

print("The original array is:")

print(ar)

print("\n")

print("The flattened array is:")

print(ar.ravel())

Output:

The original array is:

[[1 2 3 4 5]

[5 4 3 2 1]]
The flattened array is:

[1 2 3 4 5 5 4 3 2 1]

Flatten Vs Ravel

Numpy flatten() Numpy ravel()

flatten() function returns a flattened ravel() function simply returns


copy of Numpy array. a flattened view of Numpy array.
Changes made to flattened array is not If you try to modify the flattened
reflected back to the original array. view then you end up with that
same change in the original array.
flatten() occupies memory so it is ravel() does not occupy memory so
considered slower than ravel() function. we can say that it is faster
than flatten()

transpose()- used to transpose a matrix

Example:

import numpy as np

ar = np.array([[1, 2],

[3, 4]])

print("The original array is:")

print(ar)

print("\n")

print("The transpose of matrix is:")

print(ar.transpose())

Output:

The original array is:

[[1 2]

[3 4]]

The transpose of matrix is:

[[1 3]

[2 4]]
concatenate()- this method is used to concatenate 2 arrays.

numpy.concatenate((a1, a2, ...), axis)


where,
axis along which arrays have to be joined. Default is 0

Example:

import numpy as np

ar1 = np.array([[1,2],[3,4]])

print("First array:")

print(ar1)

print("\n")

ar2 = np.array([[5,6],[7,8]])

print("Second array:")

print(ar2)

print("\n")

print("Joining the two arrays along axis 0:")

print(np.concatenate((ar1,ar2),axis=0))

print("\n")

print("Joining the two arrays along axis 1:")

print(np.concatenate((ar1,ar2),axis = 1))

Output:

First array:

[[1 2]

[3 4]]

Second array:

[[5 6]

[7 8]]

Joining the two arrays along axis 0:


[[1 2]

[3 4]

[5 6]

[7 8]]

Joining the two arrays along axis 1:

[[1 2 5 6]

[3 4 7 8]]

stack()-This function joins the sequence of arrays along a new axis.

numpy.stack(arrays, axis)
where,

axis in the resultant array along which the input arrays are stacked
Example:

import numpy as np

ar1 = np.array([[1,2],[3,4]])

print("First Array:")

print(ar1)

print("\n")

ar2 = np.array([[5,6],[7,8]])

print("Second Array:")

print(ar2)

print("\n")

print("Stack the two arrays along axis 0:")

print(np.stack((ar1,ar2),0))

print("\n")
print("Stack the two arrays along axis 1:' ")

print(np.stack((ar1,ar2),1))

Output:

First Array:

[[1 2]

[3 4]]

Second Array:

[[5 6]

[7 8]]Stack the two arrays along axis 0:

[[[1 2]

[3 4]]

[[5 6]

[7 8]]]

Stack the two arrays along axis 1:'

[[[1 2]

[5 6]]

[[3 4]

[7 8]]]

hstack() and vstack()- hstack stacks arrays in sequence horizontally


(column wise) and vstack stacks arrays in sequence horizontally (column
wise)

Example:

import numpy as np
ar1 = np.array([[1,2],[3,4]])

print("First Array:")

print(ar1)

print("\n")

ar2 = np.array([[5,6],[7,8]])

print("Second Array:")

print(ar2)

print("\n")

print("Horizontal stacking:")

ar3 = np.hstack((ar1,ar2))

print(ar3)

print("\n")

print("Vertical stacking:")

ar3 = np.vstack((ar1,ar2))

print(ar3)

Output:

First Array:

[[1 2]

[3 4]]

Second Array:

[[5 6]

[7 8]]

Horizontal stacking:

[[1 2 5 6]

[3 4 7 8]]

Vertical stacking:

[[1 2]

[3 4]
[5 6]

[7 8]]

split()-divides the array into sub arrays along a specified axis.

Example:

import numpy as np

ar = np.arange(12)

print("Original Array: ")

print(ar)

print("\n")

print("Split the array in 2 equal-sized subarrays:")

ar2 = np.split(ar,2)

print(ar2)

print("\n")

print("Split the array in 3 equal-sized subarrays:")

ar3 = np.split(ar,3)

print(ar3)

print("\n")

print("Split the array at index number 4 and 7")

ar4 = np.split(ar,[4,7])

print(ar4)

Output:

Original Array:

[ 0 1 2 3 4 5 6 7 8 9 10 11]

Split the array in 2 equal-sized subarrays:


[array([0, 1, 2, 3, 4, 5]), array([ 6, 7, 8, 9, 10, 11])]

Split the array in 3 equal-sized subarrays:

[array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([ 8, 9, 10, 11])]

Split the array at index number 4 and 7

[array([0, 1, 2, 3]), array([4, 5, 6]), array([ 7, 8, 9, 10, 11])]

hsplit() and vsplit(): these methods are used to split array in horizontal
and vertical manner.

Example:

import numpy as np

ar = np.array([[1,2],[3,4]])

print("Original Array")

print(ar)

print("\n")

print("Horizontal splitting:")

ar2 = np.hsplit(ar,2)

print(ar2)

print("\n")

print("Vertical splitting:")

ar2 = np.vsplit(ar,2)

print(ar2)

Output:

Original Array
[[1 2]

[3 4]]

Horizontal splitting:

[array([[1],

[3]]), array([[2],

[4]])]

Vertical splitting:

[array([[1, 2]]), array([[3, 4]])]

delete()-this method is used to delete specific element, row or column.

Example:

import numpy as np

a = np.arange(12).reshape(3,4)

print("First array:")

print(a)

print("\n")

print("Array flattened before delete operation as axis not used:")

print(np.delete(a,5))

print("\n")

print(a)

print("\n\nRow 2 deleted:")

print(np.delete(a,1,axis=0))

print("\n")

print("\nColumn 2 deleted:")

print(np.delete(a,1,axis=1))
Output:

First array:

[[ 0 1 2 3]

[ 4 5 6 7]

[ 8 9 10 11]]

Array flattened before delete operation as axis not used:

[ 0 1 2 3 4 6 7 8 9 10 11]

[[ 0 1 2 3]

[ 4 5 6 7]

[ 8 9 10 11]]

Row 2 deleted:

[[ 0 1 2 3]

[ 8 9 10 11]]

Column 2 deleted:

[[ 0 2 3]

[ 4 6 7]

[ 8 10 11]]

unique()-this method is used to find unique values from an array.

Example:

import numpy as np

ar = np.array([1,1,2,2,3,3,4,4,5,5,6,6,7,7])

print("Array:")

print(ar)

print("\n")

print("Unique values of first array:")

unik = np.unique(ar)

print(unik)

Output:
Array:

[1 1 2 2 3 3 4 4 5 5 6 6 7 7]

Unique values of first array:

[1 2 3 4 5 6 7]

You might also like