NumPy is a Python package that provides multidimensional array and matrix objects as well as tools to work with these objects. It was created to handle large, multi-dimensional arrays and matrices efficiently. NumPy arrays enable fast operations on large datasets and facilitate scientific computing using Python. NumPy also contains functions for Fourier transforms, random number generation and linear algebra operations.
( Python Training: https://www.edureka.co/python )
This Edureka Python Numpy tutorial (Python Tutorial Blog: https://goo.gl/wd28Zr) explains what exactly is Numpy and how it is better than Lists. It also explains various Numpy operations with examples.
Check out our Python Training Playlist: https://goo.gl/Na1p9G
This tutorial helps you to learn the following topics:
1. What is Numpy?
2. Numpy v/s Lists
3. Numpy Operations
4. Numpy Special Functions
( Python Training: https://www.edureka.co/python )
This Edureka Python Numpy tutorial (Python Tutorial Blog: https://goo.gl/wd28Zr) explains what exactly is Numpy and how it is better than Lists. It also explains various Numpy operations with examples.
Check out our Python Training Playlist: https://goo.gl/Na1p9G
This tutorial helps you to learn the following topics:
1. What is Numpy?
2. Numpy v/s Lists
3. Numpy Operations
4. Numpy Special Functions
Abstract: This PDSG workshop introduces the basics of Python libraries used in machine learning. Libraries covered are Numpy, Pandas and MathlibPlot.
Level: Fundamental
Requirements: One should have some knowledge of programming and some statistics.
This document is useful when use with Video session I have recorded today with execution, This is document no. 2 of course "Introduction of Data Science using Python". Which is a prerequisite of Artificial Intelligence course at Ethans Tech.
Disclaimer: Some of the Images and content have been taken from Multiple online sources and this presentation is intended only for Knowledge Sharing
Introduction to Python Pandas for Data AnalyticsPhoenix
Pandas is an open-source, BSD-licensed Python library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. Python with Pandas is used in a wide range of fields including academic and commercial domains including finance, economics, Statistics, analytics, medical...
Looking for a computer institute to learn Full Stack development and Digital Marketing? Our institute offers comprehensive courses in both areas, providing students with the skills and knowledge needed to succeed in today's digital landscape
Python libraries presentation Contains all top 10 labraries information like numpy,tenslorflow,scikit-learn,Numpy,keras,PyToruch,LightGBM,Eli5,scipy,theano,pandas
Regular expressions are used to identify whether a pattern exists in a given sequence of characters (string) or not. They help in manipulating textual data, which is often a pre-requisite for data science projects that involve text mining. You must have come across some application of regular expressions: they are used at the server side to validate the format of email addresses or password during registration, used for parsing text data files to find, replace or delete certain string, etc.
Abstract: This PDSG workshop introduces the basics of Python libraries used in machine learning. Libraries covered are Numpy, Pandas and MathlibPlot.
Level: Fundamental
Requirements: One should have some knowledge of programming and some statistics.
This document is useful when use with Video session I have recorded today with execution, This is document no. 2 of course "Introduction of Data Science using Python". Which is a prerequisite of Artificial Intelligence course at Ethans Tech.
Disclaimer: Some of the Images and content have been taken from Multiple online sources and this presentation is intended only for Knowledge Sharing
Introduction to Python Pandas for Data AnalyticsPhoenix
Pandas is an open-source, BSD-licensed Python library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. Python with Pandas is used in a wide range of fields including academic and commercial domains including finance, economics, Statistics, analytics, medical...
Looking for a computer institute to learn Full Stack development and Digital Marketing? Our institute offers comprehensive courses in both areas, providing students with the skills and knowledge needed to succeed in today's digital landscape
Python libraries presentation Contains all top 10 labraries information like numpy,tenslorflow,scikit-learn,Numpy,keras,PyToruch,LightGBM,Eli5,scipy,theano,pandas
Regular expressions are used to identify whether a pattern exists in a given sequence of characters (string) or not. They help in manipulating textual data, which is often a pre-requisite for data science projects that involve text mining. You must have come across some application of regular expressions: they are used at the server side to validate the format of email addresses or password during registration, used for parsing text data files to find, replace or delete certain string, etc.
Introduction to NumPy, NumPy Installation, Data Types, NumPy ndarray, Basic Indexing and Slicing, Boolean Indexing, Fancy Indexing, Data Processing using Arrays, Expressing Conditional Logic, Methods for Boolean Arrays, Sorting, Unique.
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
Homework Assignment – Array Technical Document
Write a technical document that describes the structure and use of arrays. The document should
be 3 to 5 pages and include an Introduction section, giving a brief synopsis of the document and
arrays, a Body section, describing arrays and giving an annotated example of their use as a
programming construct, and a conclusion to revisit important information about arrays described
in the Body of the document. Some suggested material to include:
Declaring arrays of various types
Array pointers
Printing and processing arrays
Sorting and searching arrays
Multidimensional arrays
Indexing arrays of various dimension
Array representation in memory by data type
Passing arrays as arguments
If you find any useful images on the Internet, you can use them as long as you cite the source in
end notes.
Solution
Array is a collection of variables of the same type that are referenced by a common name.
Specific elements or variables in the array are accessed by means of index into the array.
If taking about C, In C all arrays consist of contiguous memory locations. The lowest address
corresponds to the first element in the array while the largest address corresponds to the last
element in the array.
C supports both single and multi-dimensional arrays.
1) Single Dimension Arrays:-
Syntax:- type var_name[size];
where type is the type of each element in the array, var_name is any valid identifier, and size is
the number of elements in the array which has to be a constant value.
*Array always use zero as index to first element.
The valid indices for array above are 0 .. 4, i.e. 0 .. number of elements - 1
For Example :- To load an array with values 0 .. 99
int x[100] ;
int i ;
for ( i = 0; i < 100; i++ )
x[i] = i ;
To determine to size of an array at run time the sizeof operator is used. This returns the size in
bytes of its argument. The name of the array is given as the operand
size_of_array = sizeof ( array_name ) ;
2) Initialisg array:-
Arrays can be initialised at time of declaration in the following manner.
type array[ size ] = { value list };
For Example :-
int i[5] = {1, 2, 3, 4, 5 } ;
i[0] = 1, i[1] = 2, etc.
The size specification in the declaration may be omitted which causes the compiler to count the
number of elements in the value list and allocate appropriate storage.
For Example :- int i[ ] = { 1, 2, 3, 4, 5 } ;
3) Multidimensional array:-
Multidimensional arrays of any dimension are possible in C but in practice only two or three
dimensional arrays are workable. The most common multidimensional array is a two
dimensional array for example the computer display, board games, a mathematical matrix etc.
Syntax :type name [ rows ] [ columns ] ;
For Example :- 2D array of dimension 2 X 3.
int d[ 2 ] [ 3 ] ;
A two dimensional array is actually an array of arrays, in the above case an array of two integer
arrays (the rows) each with three elements, and is stored row-wise in memory.
For Example :- Program to fill .
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...HendraPurnama31
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkualitas publikasi dalam berbagai format cetak dan lingkungan interaktif di berbagai platform.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
We all have good and bad thoughts from time to time and situation to situation. We are bombarded daily with spiraling thoughts(both negative and positive) creating all-consuming feel , making us difficult to manage with associated suffering. Good thoughts are like our Mob Signal (Positive thought) amidst noise(negative thought) in the atmosphere. Negative thoughts like noise outweigh positive thoughts. These thoughts often create unwanted confusion, trouble, stress and frustration in our mind as well as chaos in our physical world. Negative thoughts are also known as “distorted thinking”.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
How to Split Bills in the Odoo 17 POS ModuleCeline George
Bills have a main role in point of sale procedure. It will help to track sales, handling payments and giving receipts to customers. Bill splitting also has an important role in POS. For example, If some friends come together for dinner and if they want to divide the bill then it is possible by POS bill splitting. This slide will show how to split bills in odoo 17 POS.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
2. NumPy Introduction
NumPy stands for numeric python which is a python package for the
computation and processing of the multidimensional and single
dimensional array elements.
Travis Oliphant created NumPy package in 2005 by injecting the features
of the ancestor module Numeric into another module Numarray.
It is an extension module of Python which is mostly written in C. It provides
various functions which are capable of performing the numeric
computations with a high speed.
3. The need of NumPy
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.
• NumPy performs array-oriented computing.
• It efficiently implements the multidimensional arrays.
• It performs scientific computations.
• It is capable of performing Fourier Transform and reshaping the data
stored in multidimensional arrays.
• 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.
4. NumPy Environment Setup
NumPy doesn't come bundled with Python. We have to install it using the
python pip installer. Execute the following command.
Now, open a cmd window like before. Use the next set of commands to
install NumPy, SciPy and Matplotlib:
python -m pip install numpy
5. NumPy Ndarray
Ndarray is the n-dimensional array object defined in the numpy which
stores the collection of the similar type of elements. In other words, we can
define a ndarray as the collection of the data type (dtype) objects.
The ndarray object can be accessed by using the 0 based indexing. Each
element of the Array object contains the same size in the memory.
6. Creating a ndarray object
The ndarray object can be created by using the array routine of the numpy
module. For this purpose, we need to import the numpy.
Example
import numpy
a = numpy.array
print(a)
Example
import numpy
a = numpy.array([[1, 2, 3], [4, 5, 6]])
print(a.ndim)
7. The more important attributes of an ndarray object are:
ndarray.ndim
the number of axes (dimensions) of the array.
ndarray.shape
the dimensions of the array. This is a tuple of integers
indicating the size of the array in each dimension. For a
matrix with n rows and m columns, shape will be (n,m).
The length of the shape tuple is therefore the number of
axes, ndim.
ndarray.size
the total number of elements of the array. This is equal
to the product of the elements of shape.
8. ndarray.dtype
an object describing the type of the elements in the array.
One can create or specify dtype’s using standard Python
types. Additionally NumPy provides types of its own.
numpy.int32, numpy.int16, and numpy.float64 are some
examples.
ndarray.itemsize
the size in bytes of each element of the array. For example, an
array of elements of type float64 has itemsize 8 (=64/8),
while one of type complex32 has itemsize 4 (=32/8). It is
equivalent to ndarray.dtype.itemsize.
ndarray.data
the buffer containing the actual elements of the array.
Normally, we won’t need to use this attribute because we will
access the elements in an array using indexing facilities.
9. Finding the data type of each array item
To check the data type of each array item, the dtype function is used.
Consider the following example to check the data type of the array items.
import numpy as np
a = np.array([[1,2,3]])
print("Each item is of the type",a.dtype)
10. Finding the shape and size of the array
To get the shape and size of the array, the size and shape function
associated with the numpy array is used.
Consider the following example.
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print("Array Size:",a.size)
print("Shape:",a.shape)
11. Reshaping the array objects
By the shape of the array, we mean the number of rows and columns of a
multi-dimensional array. However, the numpy module provides us the way
to reshape the array by changing the number of rows and columns of the
multi-dimensional array.
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print("printing the original array..")
print(a)
a=a.reshape(2,3)
print("printing the reshaped array..")
print(a)
3*2 2*3
12. Slicing in the Array
Slicing in the NumPy array is the way to extract a range of elements from an
array. Slicing in the array is performed in the same way as it is performed in
the python list.
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print(a[0,1])
print(a[2,0])
Output:
2
5
The above program prints the 2nd element from the 0th index and 0th
element from the 2nd index of the array.
13. Slicing in the Array
Slicing in the NumPy array is the way to extract a range of elements from an
array. Slicing in the array is performed in the same way as it is performed in
the python list.
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print(a[0,1])
print(a[2,0])
Output:
2
5
The above program prints the 2nd element from the 0 th index and 0 th
element from the 2nd index of the array.
14. Linspace
The linspace() function returns the evenly spaced values over the given
interval. The following example returns the 10 evenly separated values over
the given interval 5-15
import numpy as np
a=np.linspace(5,15,10)
print(a)
Output:
[ 5. 6.11111111 7.22222222 8.33333333 9.44444444 10.55555556 11.66666667
12.77777778 13.88888889 15. ]
15. Finding the maximum, minimum, and sum
of the array elements
The NumPy provides the max(), min(), and sum() functions which are used
to find the maximum, minimum, and sum of the array elements
respectively.
import numpy as np
a = np.array([1,2,3,10,15,4])
print("The array:",a)
print("The maximum element:",a.max())
print("The minimum element:",a.min())
print("The sum of the elements:",a.sum())
16. NumPy Array Axis
A NumPy multi-dimensional array is represented by the axis where axis-0
represents the columns and axis-1 represents the rows. We can mention the
axis to perform row-level or column-level calculations like the addition of
row or column elements.
To calculate the maximum element among each column, the minimum
element among each row, and the addition of all the row elements, consider
the following example.
17. NumPy Array Axis
Example
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
print("The array:",a)
print("The maximum elements of columns:",a.max(axis = 0))
print("The minimum element of rows",a.min(axis = 1))
print("The sum of all rows",a.sum(axis = 1))
Output:
The array: [[1 2 30]
[10 15 4]]
The maximum elements of columns: [10 15 30]
The minimum element of rows [1 4] The sum of all rows [33 29]
18. Finding square root and standard Deviation
The sqrt() and std() functions associated with the numpy array are used to
find the square root and standard deviation of the array elements
respectively.
Standard deviation means how much each element of the array varies from
the mean value of the numpy array.
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
print(np.sqrt(a))
print(np.std(a))
19. Arithmetic operations on the array
The numpy module allows us to perform the arithmetic operations on
multi-dimensional arrays directly.
In the following example, the arithmetic operations are performed on the
two multi-dimensional arrays a and b.
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
b = np.array([[1,2,3],[12, 19, 29]])
print("Sum of array a and bn",a+b)
print("Product of array a and bn",a*b)
print("Division of array a and bn",a/b)
20. Array Concatenation
The numpy provides us with the vertical stacking and horizontal stacking
which allows us to concatenate two multi-dimensional arrays vertically or
horizontally.
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
b = np.array([[1,2,3],[12, 19, 29]])
print("Arrays vertically concatenatedn",np.vstack((a,b)));
print("Arrays horizontally concatenatedn",np.hstack((a,b)))
21. NumPy Datatypes
SN Data type Description
1 bool_
It represents the boolean value indicating true or false. It is stored
as a byte.
2 int_
It is the default type of integer. It is identical to long type in C
that contains 64 bit or 32-bit integer.
3 intc It is similar to the C integer (c int) as it represents 32 or 64-bit int.
4 intp It represents the integers which are used for indexing.
5 int8
It is the 8-bit integer identical to a byte. The range of the value is -
128 to 127.
6 int16 It is the 2-byte (16-bit) integer. The range is -32768 to 32767.
7 int32
It is the 4-byte (32-bit) integer. The range is -2147483648 to
2147483647.
8 int64
It is the 8-byte (64-bit) integer. The range is -
9223372036854775808 to 9223372036854775807.
9 uint8 It is the 1-byte (8-bit) unsigned integer.
10 uint16 It is the 2-byte (16-bit) unsigned integer.
11 uint32 It is the 4-byte (32-bit) unsigned integer.
22. NumPy Datatypes
SN Data type Description
12 uint64 It is the 8 bytes (64-bit) unsigned integer.
13 float_ It is identical to float64.
14 float16
It is the half-precision float. 5 bits are reserved for the
exponent. 10 bits are reserved for mantissa, and 1 bit is
reserved for the sign.
15 float32
It is a single precision float. 8 bits are reserved for the
exponent, 23 bits are reserved for mantissa, and 1 bit is
reserved for the sign.
16 float64
It is the double precision float. 11 bits are reserved for the
exponent, 52 bits are reserved for mantissa, 1 bit is used
for the sign.
17 complex_ It is identical to complex128.
23. NumPy Datatypes
SN Data type Description
18
complex6
4
It is used to represent the complex number where real
and imaginary part shares 32 bits each.
19
complex1
28
It is used to represent the complex number where real
and imaginary part shares 64 bits each.
12 uint64 It is the 8 bytes (64-bit) unsigned integer.
13 float_ It is identical to float64.
14 float16
It is the half-precision float. 5 bits are reserved for the
exponent. 10 bits are reserved for mantissa, and 1 bit is
reserved for the sign.
18
complex6
4
It is used to represent the complex number where real
and imaginary part shares 32 bits each.
24. Numpy Array Creation
The ndarray object can be constructed by using the following routines.
Numpy.empty
import numpy as np
arr = np.empty((3,2),
dtype = int)
print(arr)
Output:
[[1 0]
[4 0]
[0 0]]
NumPy.Zeros
import numpy as np
arr = np.zeros((3,2),
dtype = int)
print(arr)
Output
[[0 0]
[0 0]
[0 0]]
NumPy.ones
import numpy as np
arr = np.ones((3,2),
dtype = int)
print(arr)
Output
[[1 1]
[1 1]
[1 1]]
25. Numpy Array from Existing Data
NumPy provides us the way to create an array by using the existing
data.
This routine is used to create an array by using the existing data in the
form of lists, or tuples. This routine is useful in the scenario where we
need to convert a python sequence into the numpy array object.
numpy.asarray(sequence, dtype = None, order = None)
It accepts the following parameters.
• sequence: It is the python sequence which is to be converted into
the python array.
• dtype: It is the data type of each item of the array.
• order: It can be set to C or F. The default is C.
26. Numpy Array from Existing Data
Creating numpy array using the list
import numpy as np
l=[1,2,3,4,5,6,7]
a = np.asarray(l);
Creating a numpy array using Tuple
import numpy as np
l=(1,2,3,4,5,6,7)
a = np.asarray(l)
Creating a numpy array using more than one list
import numpy as np
l=[[1,2,3,4,5,6,7],[8,9]]
a = np.asarray(l);
27. Numpy Arrays within the numerical range
This section of the tutorial illustrates how the numpy arrays can be
created using some given specified range.
Numpy.arrange
numpy.arrange(start, stop, step, dtype)
Example
import numpy as np
arr = np.arange(0,10,2,float)
print(arr)
Output:
[0. 2. 4. 6. 8.]
28. NumPy Broadcasting
In Mathematical operations, we may need to consider the arrays of
different shapes. NumPy can perform such operations where the array
of different shapes are involved.
For example, if we consider the matrix multiplication operation, if the
shape of the two matrices is the same then this operation will be easily
performed
import numpy as np
a = np.array([1,2,3,4,5,6,7])
b = np.array([2,4,6,8,10,12,14])
c = a*b;
print(c)
Output:
[ 2 8 18 32 50 72 98]
29. NumPy Broadcasting
If we consider arrays of different shapes, we will get the errors as shown
below.
import numpy as np
a = np.array([1,2,3,4,5,6,7])
b = np.array([2,4,6,8,10,12,14,19])
c = a*b;
print(c)
Output:
ValueError: operands could not be broadcast together with shapes (7,) (8,)
NumPy can perform such operation by using the concept of
broadcasting.
30. Broadcasting Rules
Broadcasting is possible if the following cases are satisfied.
• The smaller dimension array can be appended with '1' in its shape.
• Size of each output dimension is the maximum of the input sizes in the
dimension.
• An input can be used in the calculation if its size in a particular dimension
matches the output size or its value is exactly 1.
• If the input size is 1, then the first data entry is used for the calculation along the
dimension.
Broadcasting can be applied to the arrays if the following rules are satisfied.
1. All the input arrays have the same shape.
2. Arrays have the same number of dimensions, and the length of each dimension
is either a common length or 1.
3. Array with the fewer dimension can be appended with '1' in its shape.
31. Broadcasting Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
b = np.array([2,4,6,8])
print("nprinting array a..")
print(a)
print("nprinting array b..")
print(b)
print("nAdding arrays a and b ..")
c = a + b;
print(c)
32. NumPy Array Iteration
NumPy provides an iterator object, i.e., nditer which can be used to iterate
over the given array using python standard Iterator interface.
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("Printing array:")
print(a);
print("Iterating over the array:")
for x in np.nditer(a):
print(x,end=' ')
33. NumPy Bitwise Operators
SN Operator Description
1 bitwise_and
It is used to calculate the bitwise and operation
between the corresponding array elements.
2 bitwise_or
It is used to calculate the bitwise or operation
between the corresponding array elements.
3 invert
It is used to calculate the bitwise not the operation
of the array elements.
4 left_shift
It is used to shift the bits of the binary
representation of the elements to the left.
5 right_shift
It is used to shift the bits of the binary
representation of the elements to the right.
34. NumPy Bitwise Operators
Example
import numpy as np
a = 10
b = 12
print("binary representation of a:",bin(a))
print("binary representation of b:",bin(b))
print("Bitwise-and of a and b: ",np.bitwise_and(a,b))
Output:
binary representation of a: 0b1010
binary representation of b: 0b1100
Bitwise-and of a and b: 8
35. NumPy String Functions
SN Function Description
1 add()
It is used to concatenate the corresponding array elements
(strings).
2 multiply()
It returns the multiple copies of the specified string, i.e., if a
string 'hello' is multiplied by 3 then, a string 'hello hello' is
returned.
3 center()
It returns the copy of the string where the original string is
centered with the left and right padding filled with the
specified number of fill characters.
4 capitalize()
It returns a copy of the original string in which the first letter
of the original string is converted to the Upper Case.
5 title()
It returns the title cased version of the string, i.e., the first
letter of each word of the string is converted into the upper
case.
6 lower()
It returns a copy of the string in which all the letters are
converted into the lower case.
36. NumPy String Functions
SN Function Description
7 upper()
It returns a copy of the string in which all the letters are
converted into the upper case.
9 split() It returns a list of words in the string.
9 splitlines()
It returns the list of lines in the string, breaking at line
boundaries.
10 strip()
Returns a copy of the string with the leading and trailing
white spaces removed.
11 join()
It returns a string which is the concatenation of all the
strings specified in the given sequence.
12 replace()
It returns a copy of the string by replacing all occurrences of
a particular substring with the specified one.
37. NumPy String Functions
numpy.char.add() method example
import numpy as np
print("Concatenating two string arrays:")
print(np.char.add(['welcome','Hi'], [' to Nielit', ' read AI'] ))
Output
Concatenating two string arrays:
['welcome to Nielit' 'Hi read AI']
38. NumPy String Functions
numpy.char.multiply() method example
import numpy as np
print("Printing a string multiple times:")
print(np.char.multiply("hello ",3))
Output
Printing a string multiple times:
hello hello hello
39. NumPy String Functions
numpy.char.capitalize() method example
import numpy as np
print("Capitalizing the string using capitalize()...")
print(np.char.capitalize("welcome to nielit"))
Output
Capitalizing the string using capitalize()...
Welcome to nielit
40. NumPy String Functions
numpy.char.split() method example
import numpy as np
print("Splitting the String word by word..")
print(np.char.split("Welcome To NIELIT"),sep = " ")
Output
Splitting the String word by word..
['Welcome', 'To', 'NIELIT']
41. NumPy Mathematical Functions
Numpy contains a large number of mathematical functions which can
be used to perform various mathematical operations. The mathematical
functions include trigonometric functions, arithmetic functions, and
functions for handling complex numbers. Let's discuss the
mathematical functions.
import numpy as np
arr = np.array([0, 30, 60, 90, 120, 150, 180])
print("nThe sin value of the angles",end = " ")
print(np.sin(arr * np.pi/180))
print("nThe cosine value of the angles",end = " ")
print(np.cos(arr * np.pi/180))
print("nThe tangent value of the angles",end = " ")
print(np.tan(arr * np.pi/180))
42. Numpy statistical functions
Numpy provides various statistical functions which are used to perform
some statistical data analysis. In this section of the tutorial, we will
discuss the statistical functions provided by the numpy.
import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print("Array:n",a)
print("nMedian of array along axis 0:",np.median(a,0))
print("Mean of array along axis 0:",np.mean(a,0))
print("Average of array along axis 1:",np.average(a,1))
43. NumPy Sorting and Searching
numpy.sort(a, axis, kind, order)
It accepts the following parameters.
SN Parameter Description
1 input It represents the input array which is to be sorted.
2 axis
It represents the axis along which the array is to be
sorted. If the axis is not mentioned, then the sorting is
done along the last available axis.
3 kind
It represents the type of sorting algorithm which is to
be used while sorting. The default is quick sort.
4 order
It represents the filed according to which the array is
to be sorted in the case if the array contains the fields.
44. NumPy Sorting and Searching
import numpy as np
a = np.array([[10,2,3],[4,5,6],[7,8,9]])
print("Sorting along the columns:")
print(np.sort(a))
print("Sorting along the rows:")
print(np.sort(a, 0))
data_type = np.dtype([('name', 'S10'),('marks',int)])
arr = np.array([('Mukesh',200),('John',251)],dtype = data_type)
print("Sorting data ordered by name")
print(np.sort(arr,order = 'name'))