What is NumPy?
•NumPy is a Python library used for working with
arrays.
• It also has functions for working in domain of
linear algebra, fourier transform, and matrices.
• NumPy was created in 2005 by Travis Oliphant.
It is an open source project and you can use it
freely.
• NumPy stands for Numerical Python.
3.
Why Use NumPy?
•In Python we have lists that serve the purpose of
arrays, but they are slow to process.
• 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.
4.
Why is NumPyFaster 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.
5.
Vectorization in NumPywith Practical Examples
• Vectorization in NumPy is a method
of performing operations on entire arrays
without explicit loops. This approach leverages
NumPy’s underlying C implementation for
faster and more efficient computations.
• By replacing iterative processes with vectorized
functions, you can significantly optimize
performance in data analysis, machine
learning, and scientific computing tasks.
Vectorization is significantbecause it:
• Improves Performance: Operations are faster
due to pre-compiled C-based
implementations.
• Simplifies Code: Eliminates explicit loops,
making code cleaner and easier to read.
• Supports Scalability: Efficiently handles large
datasets.
8.
Adding two arraystogether with vectorization
import numpy as np
a1 = np.array([1, 2, 3])
a2 = np.array([4, 5, 6])
result = a1 + a2
print(result)
Output[5 7 9]
Applying Custom Functionswith Numpy Vectorize() Function
import numpy as np
def custom_func(x):
return x**2 + 2*x + 1
a1 = np.array([1, 2, 3, 4])
result = custom_func(a1)
print(result)
13.
PANDAS
• Pandas isone of the most used libraries in
Python for data science or data analysis. It can
read data from CSV or Excel files, manipulate
the data, and generate insights from it. Pandas
can also be used to clean data, filter data, and
visualize data.
14.
List of ImportantPandas Functions
• Pandas read_csv() Function
• Pandas head() Function
• Pandas tail() Function
• Pandas sample() Function:This method is used to
generate a sample random row or column from the data
frame.
• Pandas info() Function:This method is used to generate
the summary of the DataFrame, this will include info
about columns with their names, their datatypes, and
missing values.
• Pandas dtypes() Function:This method returns a Series
with the data type of each column.
15.
Python Pandas Series
•Pandas Series is a one-dimensional labeled
array capable of holding data of any type
(integer, string, float, python objects, etc.).
# import pandas as pd
import pandas as pd
# simple array
data = [1, 2, 3, 4]
ser = pd.Series(data)
print(ser)
Output
0 1
1 2
2 3
3 4
dtype: int64
16.
Creating a PandasSeries
# import pandas as pd
import pandas as pd
# import numpy as np
import numpy as np
# simple array
data = np.array(['g','e','e','k','s'])
ser = pd.Series(data)
print(ser)
Output
0 g
1 e
2 e
3 k
4 s
dtype: object
Indexing And Slicing
•Indexing is the process of accessing an
element in a sequence using its position in the
sequence (its index).
• In Python, indexing starts from 0, which
means the first element in a sequence is at
position 0, the second element is at position 1,
and so on.
• Slicing inPython
• Slicing is the process of accessing a sub-
sequence of a sequence by specifying a
starting and ending index. In Python, you
perform slicing using the colon : operator.
• sequence[start_index:end_index]
• In thefirst line of the above code, we have
used slicing to get all the elements from the
beginning of my_list up to (but not including)
the element at index 2. In the second line, we
have used slicing to get all the elements from
index 2 to the end of my_list.
24.
• numbers =[1, 2, 3, 4, 5, 6, 7, 8, 9]
odd_numbers = numbers[::2]
print(odd_numbers) # output: [1, 3, 5, 7, 9]
• The ::2 slice means that we are selecting every
other element starting from the first element,
which correspond to the odd numbers in the
list
25.
• The ::2slice means that we are selecting every
other element starting from the first element,
which correspond to the odd numbers in the
list
26.
Concatenation
• Concatenation isdone by + operator.
Concatenation is supported by sequence data
types(string, list, tuple). Concatenation is done
between the same data types only.
Repetition
• Sequences datatypes(both mutable and
immutable) support repetition operator * The
repetition operator * will make multiple
copies of that particular object and combines
them together. When * is used with an integer
it performs multiplication but with list, tuple
or strings it performs a repetition
Add/Remove Set Items
•Add items to set:
• If you want to add a single item to the set use
the add() method.
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.add("Helsinki")
print(cities)
Output:
{'Tokyo', 'Helsinki', 'Madrid', 'Berlin', 'Delhi'}
Remove items fromset:
• We can use remove() and discard() methods
to remove items form list.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.remove("Tokyo")
print(cities)
34.
pop():
This method removesthe last item of the set but the catch is that we
don’t know which item gets popped as sets are unordered. However, you
can access the popped item if you assign the pop() method to a variable.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
item = cities.pop()
print(cities)
print(item)
Output:
{'Tokyo', 'Delhi', 'Berlin'}
Madrid
35.
del:
del is nota method, rather it is a keyword which
deletes the set entirely.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
del cities
print(cities)
36.
clear():
This method clearsall items in the set and prints
an empty set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.clear()
print(cities)
37.
Sorted() Method
This isa pre-defined method in python which sorts
any kind of object.
Syntax:sorted(iterable, key, reverse)
In this method, we pass 3 parameters, out of which
2 (key and reverse) are optional and the first
parameter i.e. iterable can be any iterable object
This method returns a sorted list but does not
change the original data structure.
• The reverse()method reverses the elements
of the list in-place and it modify the original
list without creating a new list. This method is
efficient because it doesn’t create a new list.
a = [1, 2, 3, 4, 5]
# Reverse the list in-place
a.reverse()
print(a)
40.
Using the reversed()
Python’sbuilt-in reversed() function is another
way to reverse the list. However, reversed() returns an
iterator, so it needs to be converted back into a list.
a = [1, 2, 3, 4, 5]
# Use reversed() to create an iterator
# and convert it back to a list
rev = list(reversed(a))
print(rev)