Exploratory Data Analysis With Python - Notes I
Exploratory Data Analysis With Python - Notes I
UNIT-I
Introduction to EDA and Python Environment
Data Science is a multidisciplinary field that combines statistical methods, programming skills, and domain
knowledge to extract meaningful insights and knowledge from structured and unstructured data. It is at
the heart of modern technological advancements, empowering industries to make data−driven decisions and
innovate rapidly.
Data Science involves the process of collecting, processing, analyzing, and interpreting data to uncover
patterns and support decision−making. It draws techniques from fields such as:
1. Data Collection: Gathering data from various sources such as databases, web APIs, sensors, or
spreadsheets.
2. Data Cleaning and Preprocessing: Handling missing values, removing noise, and converting raw
data into usable formats.
s. Exploratory Data Analysis (EDA): Visualizing and summarizing the main characteristics of data
using graphs and statistics.
4. Data Modeling: Applying algorithms (e.g., regression, classification, clustering) to find patterns or
make predictions.
5. Model Evaluation: Assessing the performance of models using metrics like accuracy, precision,
recall, or RMSE.
a. Deployment and Visualization: Presenting the results in interactive dashboards or embedding
models in applications for real−time usage.
1. Problem Definition
This is the most critical phase, as a poorly defined problem leads to poor outcomes.
Key questions:
• What is the business problem?
Example:
For a bank, the goal might be predicting loan default to reduce risk.
2. Data Collection
Once the problem is defined, the next step is to gather relevant data.
Sources:
• Databases (MySQL, MongoDB)
• APIs (Twitter API, Weather API)
• Web scraping
• Public datasets (Kaggle, UCI, [Link])
• IoT devices or mobile applications
Activities:
• Identify relevant data sources
• Connect and extract data
• Store in a data warehouse or data lake
6. Model Building
This is the core stage where machine learning or statistical models are trained to learn from the data.
Model Types:
• Supervised Learning: Regression, Classification
• Unsupervised Learning: Clustering, Dimensionality Reduction
• Reinforcement Learning: Agent−based decision making
Process:
• Split data into training and testing sets
• Choose algorithms (e.g., decision trees, SVM, neural networks)
• Train the model on the training data
7. Model Evaluation
The model is assessed for its performance using various metrics, depending on the problem type.
Common Metrics:
• Accuracy, Precision, Recall, F1−score (for classification)
• RMSE, MAE, R² (for regression)
• Confusion matrix, ROC−AUC curve
Techniques:
• Cross−validation
• Hyperparameter tuning
• Model comparison
8. Model Deployment
Once a model performs well, it’s deployed to make real−time or batch predictions.
Deployment Methods:
• REST APIs
• Web applications (Flask, Django)
• Cloud platforms (AWS SageMaker, GCP AI Platform)
Considerations:
• Scalability
• Monitoring and feedback loops
• Version control
Introduction to NumPy
NumPy (Numerical Python) is a fundamental package for scientific computing in Python. It provides
efficient arrays, mathematical functions, and tools for working with large, multi-dimensional data. It
is the foundation for many libraries in data science and machine learning, such as Pandas, SciPy, and
TensorFlow.
Installing NumPy
Using pip:
pip install numpy
Basic Example
import numpy as np
# Create a 1D array
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
# Create a 2D array (matrix)
mat = [Link]([[1, 2], [3, 4]])
print(mat)
Numpy Operations
Installing Pandas
Using pip:
pip install pandas
Basic Example:
Series – One−dimensional Arrays
import pandas as pd
s = [Link]([10, 20, 30, 40])
print(s)
#Output
0 10
1 20
2 30
3 40
dtype: int64
import pandas as pd
data = {
'Name': ['Mahesh', 'Paani', 'Suresh'],
'Age': [25, 30, 35],
'City': ['Chennai', 'Bangalore', 'Tirupati']
}
df = [Link](data)
print(df)
#Output
Name Age City
o Mahesh 25 Chennai
1 Paani so Bangalore
2 Suresh s5 Tirupati
Pandas Operations
Basic Operations
1. Create DataFrame
import pandas as pd
data = {
'Name': ['Mahesh', 'Paani', 'Suresh'],
'Age': [25, 30, 35],
'City': ['Chennai', 'Bangalore', 'Tirupati']
}
df = [Link](data)
print(df)
#Output
Name Age City
o Mahesh 25 Chennai
1 Paani so Bangalore
2 Suresh s5 Tirupati
2. info()
Syntax: info()
import pandas as pd
data = {
'Name': ['Mahesh', 'Paani', 'Suresh'],
'Age': [25, 30, 35],
'City': ['Chennai', 'Bangalore', 'Tirupati']
}
df = [Link](data)
[Link]()
#Output
<class '[Link]'>
RangeIndex: s entries, o to 2
Data columns (total s columns):
# Column Non−Null Count Dtype
−−− −−−−−− −−−−−−−−−−−−−− −−−−−
o Name s non−null object
1 Age s non−null inta4
2 City s non−null object
dtypes: inta4(1), object(2)
memory usage: 2oo.o+ bytes
2. describe()
The describe() function in Pandas is used to generate summary statistics of numerical columns in a
DataFrame.
Syntax : [Link]()
Metric Meaning
count Number of non−null entries
mean Average of the values
std Standard deviation
min Minimum value
25% 1st quartile (25th percentile)
5o% Median (5oth percentile)
75% srd quartile (c5th percentile)
max Maximum value
import pandas as pd
data = {
'Name': ['Mahesh', 'Paani', 'Suresh'],
'Age': [25, 30, 35],
'City': ['Chennai', 'Bangalore', 'Tirupati']
}
df = [Link](data)
print([Link]())
#Output
Age
count [Link]
mean [Link]
std [Link]
min [Link]
25% 2c.5ooooo
5o% [Link]
c5% s2.5ooooo
max [Link]
Note: describe () by default only includes numeric columns. To include all columns (including object
types like strings), use:
[Link](include='all')
3. [Link]
[Link] returns a tuple representing the dimensions of a [Link] in terms of (rows, columns)
Syntax:
[Link]
Example:
import pandas as pd
data = {
'Name': ('Mahesh', 'Paani', 'Suresh'),
'Age': (25, 3o, 35),
'City': ('Chennai', 'Banglore', 'Tirupati')
}
df = [Link](data)
print([Link])
#Output
(3, 3)
Output Explanation
s rows → one for each person: Mahesh, Paani, Suresh
s columns → Name, Age, City
Introduction
This tutorial will show you how to: i) install Python with Anaconda-Navigator (Section 1);
ii) manage virtual environments with Anaconda (Section 2); iii) install python packages
(Section 3); iv) use Jupyter Notebook (Section 4).
1 Install Anaconda-Navigator
Anaconda Navigator is a desktop GUI (Graphical User Interface) allowing you to launch
applications and manage conda packages and environments without command-line
commands. It includes a GUI, Anaconda Navigator, as a graphical alternative to the
command line interface. Navigator can search for packages, install them in an environment,
run the packages, and update them. The Anaconda guide can be found at the following URL:
[Link]
1.1 Download Anaconda-Navigator
From the Anaconda website at the following URL:
[Link] download the installation files for your
operating system (i.e., MacOS, Linux, or Windows). Install the latest version of python with
16
1.2 Install Anaconda-Navigator
When the download is finished, double-click on the downloaded file in the bottom left-hand
corner of your browser. This will start the installation of Anaconda-Navigator. The
installation process depends on your operating system.
18
2.3 Choose a new name for your virtual environment
You have to specify the environment name and the Python version. Then, click the "Create"
button.
19
2.4 Check the installed packages
Once created a new environment, the list of all installed packages in that environment
will be shown. Notice that some packages are already installed.
20
3 Packages
To install a new package in the virtual environment, you have two options:
• Using the Anaconda-Navigator GUI directly (Section 3.1).
• Using the command line with the conda or pip commands (Section 3.2).
The main difference between conda and the pip package manager is how the package
dependencies are managed. When pip installs a package, it also automatically installs any
dependent Python packages without checking if these conflict with previously installed
packages. Therefore, it will install a package and any of its dependencies regardless of the
state of the existing installation. In contrast, conda analyzes the current environment,
including everything currently installed and any version limitations specified. It works out
how to install a compatible set of dependencies and shows a warning if this cannot be done
[5]. Using the Anaconda-Navigator GUI to install a package will exploit the conda
package manager. You can learn more about the differences between conda and pip at
the following URL: [Link] com/blog/understanding-conda-and-pip.
21
Then search for the package that you want to install by typing the name in the
textbox (e.g., in this case, NLTK).
22
3.1.2 Select and install the required package
The Anaconda-Navigator will search in the conda repository for all the conda packages
matching the typed name. Then, select the wanted package line and click on the "Apply"
button in the right-hand bottom corner.
23
It will open a new window with all the dependencies for that package. The conda package
manager
will install all the dependencies for you. Click the "Apply" button to start the package installation.
24
Wait for the download and installation. It could take some minutes.
25
A new line corresponding to the installed package (in this case, NLTK) should appear.
26
3.1.4 Uninstall the package
To uninstall a package, click the green ✓ on the line corresponding to the package you want to
remove.
27
The green ✓ will become a red crossed box. Then, click the "Apply" button in the right-
hand bottom corner.
It will open a new window with all the packages that will be removed. Finally, click the
"Apply" button in the right-hand bottom corner to start the package uninstallation.
28
3.2 Install a package with the command line
This Section will show you how to install packages by terminal, with the pip (Section 3.2.1) and
conda (Section 3.2.2) commands. To open the terminal for your environment, select the
corresponding line and click the green ▷ symbol.
29
This will open the terminal with the selected environment activated (i.e., if you install a
package, it will be installed in the activated environment). You can see the activated environment
in the round brackets at the left of the line (e.g., mlds-env ).
Press enter on your keyboard to start the download and the installation. It could take some
minutes
30
package installation on the official documentation websites.
The terminal will show all the dependencies (i.e., other packages) that will be
installed. press y and then enter to start the download and the installation.
4 Jupyter notebook
Jupyter Notebook is a powerful tool for developing and presenting data science projects
interac-tively. In a Jupyter Notebook document, you can combine code, visualizations,
texts, and dis-play outputs. You can find a good guide at the following URL [3]:
[Link] jupyter-notebook-tutorial/.
The following sections will show you how to: i) install Jupyter notebook using Anaconda (Section 4.1);
ii) launch Jupyter from Anaconda 4.2; iii) create your first Jupyter notebook 4.3; iv) use
cells and kernels to effectively exploit Jupyter notebooks (Sections 4.4 and 4.5); v) exploit
advanced features of Jupyter notebooks (Section 4.6).
Then, click the "Install" button under the Jupyter application box.
32
This will start the download and installation process. It may require some minutes.
33
It will open the Notebook Dashboard for exploring, editing, and creating notebooks. Here
you can create new folders, notebooks, etc. The URL for the dashboard is
[Link] Localhost is not a website but indicates that the content is run on
your local machine.
34
It will create a new file [Link]. Each .ipynb file is a text file that describes the contents
of your notebook in a format called JSON. Each time you create a new notebook, a new .ipynb
file will be created. Notice that the notebook extension .ipynb is different from the normal
python file extension .py. Please rename now your filename from the top text box, or, very
soon, you will have several [Link], Untitled (1).ipynb notebooks. The notebook’s
name should explain the content.
35
4.3.1 The Jupyter Notebook interface
The two main concepts that you should learn to use notebooks properly are cells and kernels:
• The cell is a container for code to be executed or text to be displayed in the notebook by the
kernel (Section 4.4).
• The kernel is a computational engine that executes the code contained in a notebook
document (Section 4.5).
4.4 Notebook cells
Cells compose the body of the notebook. They could contain code, plain text, images, LaTeX,
math formulas, etc. There are two main cell types that you should learn:
• Code cells (Section 4.4.1)
• Markdown cells (Section 4.4.2)
4.4.1 Code cell
Code cells contain code to be executed in the kernel. When the code is run, the notebook displays
the output below the code cell that generated it. Note that cells do not have to be executed in
order. It is also possible to execute a cell at the end and then one at the beginning of the notebook.
The cell type is shown in the drop-down menu. The default type is Code.
In this case, the execution of the cell will print the string "This is my first
36
Jupyter notebook" as output. Each cell could produce an output.
The following cell will create a new variable called x and assigns the values of 10 to x. In
this case, no output is produced by the cell.
37
4.4.3 Text Markdown cell
You can write plaintext in a cell. This text is not a code. Therefore, it will not be really
executed. You can also empathize text with bold or italic with **bold** and *italic*
respectively.
38
If you run the cell containing plaintext, it will be displayed formatted as output. This can add narrative
to your Jupyter notebook.
4.4.4 Heading Markdown cell
You can also add first, second, and third-level headings.
39
OHM SRI SAIRAM
order.
OHM SRI SAIRAM
Restarting the kernel clears all the cells’ outputs and initializes the run identification
What do you think will happen if you now print the value of the variable
x again? It will raise an error message because restarting the kernel caused a
reset of the notebook status and, consequently, all the previously defined
variables.
OHM SRI SAIRAM