Python Libraries
Python Libraries
@[Link]
Pandas For
for Beginners
beginners
Easy and detailed
easy
guide
by [Link]
Chapter 1
INTRODUCTION TO
PANDAS
1. What is Pandas?
2. Use of Pandas
3. Installation and Setup
4. Overview of Pandas' Core Data Structures
What is Pandas?
Pandas is a powerful and flexible open-source data
analysis and manipulation library for Python.
It is widely used in data science and analytics to work
with structured data.
Use of Pandas
Pandas is commonly used for:
2
Installation and Setup
To get started with Pandas, you need to install it.
2
Series:
A one-dimensional array-like object that can hold
any data type (integers, strings, floats, etc.).
It is similar to a column in a spreadsheet or a
database table.
Each element in a Series is associated with an
index label.
import pandas as pd
DataFrame:
2
import pandas as pd
df = [Link]({
'A': [1, 2, 3],
'B': [4, 5, 6]
}, index=['row1', 'row2', 'row3'])
print(df)
2
Chapter 2
SERIES: THE 1D
DATA STRUCTURE
1. Creating a Series
2. Accessing Data in a Series
3. Operations on Series
Creating a Series
A Series in Pandas is a one-dimensional array-like
structure that can hold data of any type—integers,
strings, floats, etc.
import pandas as pd
2
Example 2: Creating a Series with Custom Index
import pandas as pd
import pandas as pd
2
Accessing Data in a Series
You can access the data in a Series using the index
labels or position-based indexing (similar to
accessing elements in a list or dictionary).
import pandas as pd
import pandas as pd
2
Example 3: Accessing Multiple Elements
import pandas as pd
2
Operations on Series
Pandas allows you to perform various operations on
Series, such as arithmetic operations, aggregation,
and element-wise operations.
import pandas as pd
2
Example 2: Aggregation Operations You can use
functions like sum(), mean(), min(), and max() to
perform aggregation on Series.
import pandas as pd
This will print the sum (100) and mean (25.0) of the
Series.
import pandas as pd
s = [Link]([1, 2, 3, 4])
2
This will return a Series with each element squared.
<class '[Link]'>
2
Chapter 3
DATAFRAME: THE 2D
DATA STRUCTURE
1. Creating a DataFrame
2. Accessing Data in a DataFrame
3. Adding and Removing Columns
4. DataFrame Attributes and Methods
5. Applications of DataFrame
6. Commonly used DataFrame functions
Creating a DataFrame
A DataFrame in Pandas is a two-dimensional table,
similar to a spreadsheet or a SQL table.
It consists of rows and columns, where each column
can hold different types of data (e.g., integers,
strings, floats).
You can create a DataFrame from various data
sources such as dictionaries, lists, or even external
files like CSVs.
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles',
'Chicago']
}
df = [Link](data)
print(df)
2
Accessing Data in a DataFrame
You can access data in a DataFrame using various
methods, such as accessing specific columns, rows,
or even specific elements.
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
})
2
Example 2: Accessing Multiple Columns
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
'City': ['New York', 'Los Angeles',
'Chicago']
})
2
Example 3: Accessing Rows Using .loc and .iloc
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
})
2
Example 4: Accessing Specific Elements
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
})
2
Adding and Removing Columns
Pandas makes it easy to add or remove columns in a
DataFrame.
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
})
2
Example 2: Removing a Column
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles',
'Chicago']
})
2
DataFrame Attributes and Methods
Pandas DataFrames come with several attributes and
methods that help you understand and manipulate
the data.
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
})
2
Example 2: Common Methods
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles',
'Chicago']
})
2
Applications of DataFrame
Work with Data Sets: Load and view data.
Analyze Data: Perform sorting, filtering, and
aggregation.
Clean Data: Drop or handle missing values.
Process Data: Transform and manipulate data.
Integrate Data: Merge or join multiple data
sources.
Export Data: Save to Excel, CSV, JSON, or binary
formats.
Math & Stats: Perform calculations and statistical
operations.
Group Data: Aggregate data using group by.
2
Filtering and Sorting:
[Link]()
DataFrame.sort_values()
Data Cleaning:
[Link]()
[Link]()
Data Processing:
[Link]()
Grouping and Aggregation:
[Link]()
[Link]()
Represented By:
<class '[Link]'>
2
Chapter 4
BASIC DATA
OPERATIONS
1. Indexing and Slicing
2. Filtering Data
3. Handling Missing Data
4. Sorting Data
Indexing and Slicing
Indexing and slicing help you access and manipulate
parts of your data.
For Example:
For Example:
2
And in Pandas we can do like this:
import pandas as pd
df = [Link]({
'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8]
})
print([Link][1])
# Output: A 2
# B 6
# Name: 1, dtype: int64
2
Filtering Data
Filtering helps you select specific data based on
conditions.
import pandas as pd
df = [Link]({
'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8]
})
print([Link][1])
# Output: A 2
# B 6
# Name: 1, dtype: int64
2
Multiple Conditions: Combine conditions using &
(and) or | (or).
For Example:
# Output:
# Name Age
# 1 Bob 30
2
Handling Missing Data
Handling Missing Data involves dealing with data
entries that are missing or incomplete.
For Example:
import pandas as pd
import numpy as np
df = [Link]({
'Name': ['Alice', 'Bob', [Link]],
'Age': [25, [Link], 35]
})
print([Link]()) # Output:
# Name Age
# 0 False False
# 1 False True
# 2 True False
2
Filling Missing Data: Replace missing values with a
specific value.
For Example:
# Output:
# Name Age
# 0 Alice 25.0
# 1 Bob 0.0
# 2 Unknown 35.0
2
Dropping Missing Data: Remove rows with missing
values.
For Example:
print([Link]())
# Output:
# Name Age
# 0 Alice 25.0
# 2 Unknown 35.0
2
Sorting Data
Sorting Data helps you arrange data in a specific
order.
For Example:
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
})
print(df.sort_values(by='Age'))
# Output:
# Name Age
# 0 Alice 25
# 1 Bob 30
# 2 Charlie 35
2
Sorting in Descending Order: Use ascending=False.
For Example:
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
})
print(df.sort_values(by='Age',
ascending=False))
# Output:
# Name Age
# 2 Charlie 35
# 1 Bob 30
# 0 Alice 25
2
Sorting by Multiple Columns: Sort by more than one
column.
For Example:
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie',
'Alice'],
'Age': [25, 30, 30, 20]
})
print(df.sort_values(by=['Age', 'Name']))
# Output:
# Name Age
# 3 Alice 20
# 0 Alice 25
# 1 Bob 30
# 2 Charlie 30
2
Chapter 5
DATA
MANIPULATION
1. Adding and Modifying Rows/Columns
2. Merging and Joining DataFrames
3. Concatenating DataFrames
4. Grouping and Aggregating Data
Adding and Modifying Rows/Columns
Adding and modifying rows or columns lets you
update your DataFrame with new data or adjust
existing data.
For Example:
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob'],
'Age': [25, 30]
})
df['City'] = ['New York', 'Los Angeles']
print(df)
# Output:
# Name Age City
# 0 Alice 25 New York
# 1 Bob 30 Los Angeles
2
Adding Rows: You can add a new row to a
DataFrame.
For Example:
df = [Link]([df, new_row],
ignore_index=True)
print(df)
# Output:
# Name Age City
# 0 Alice 25 New York
# 1 Bob 30 Los Angeles
# 2 Charlie 35 Chicago
2
Modifying Columns: You can update an existing
column's values.
For Example:
df['Age'] = df['Age'] + 1
print(df)
# Output:
# Name Age City
# 0 Alice 26 New York
# 1 Bob 31 Los Angeles
# 2 Charlie 36 Chicago
2
Merging and Joining DataFrames
Merging and joining combine data from multiple
DataFrames based on common columns or indices.
For Example:
df1 = [Link]({
'ID': [1, 2, 3],
'Name': ['Alice', 'Bob', 'Charlie']
})
df2 = [Link]({
'ID': [1, 2, 4],
'Age': [25, 30, 40]
})
# Output:
# ID Name Age
# 0 1 Alice 25
# 1 2 Bob 30
2
Types of Joins:
2
Concatenating DataFrames
Concatenating combines DataFrames either vertically
(adding rows) or horizontally (adding columns).
For Example:
df1 = [Link]({
'Name': ['Alice', 'Bob'],
'Age': [25, 30]
})
df2 = [Link]({
'Name': ['Charlie', 'David'],
'Age': [35, 40]
})
concatenated_df = [Link]([df1, df2],
ignore_index=True)
print(concatenated_df)
# Output:
# Name Age
# 0 Alice 25
# 1 Bob 30
# 2 Charlie 35
# 3 David 40
2
Concatenating Horizontally: Combine DataFrames
side by side.
For Example:
df1 = [Link]({
'Name': ['Alice', 'Bob'],
'Age': [25, 30]
})
df2 = [Link]({
'City': ['New York', 'Los Angeles']
})
concatenated_df = [Link]([df1, df2],
axis=1)
print(concatenated_df)
# Output:
# Name Age City
# 0 Alice 25 New York
# 1 Bob 30 Los Angeles
2
Grouping and Aggregating Data
Grouping and aggregating allow you to summarize
and analyze data by dividing it into groups based on a
specific column and then performing calculations.
For Example:
df = [Link]({
'Department': ['HR', 'Finance', 'HR',
'Finance', 'IT'],
'Employee': ['Alice', 'Bob', 'Charlie',
'David', 'Eve'],
'Salary': [50000, 60000, 55000, 62000, 70000]
})
grouped_df = [Link]('Department').mean()
print(grouped_df)
# Output:
# Salary
# Department
# Finance 61000.0
# HR 52500.0
# IT 70000.0
2
Aggregating Data: Perform calculations on each
group.
For Example:
grouped_df =
[Link]('Department').agg({'Salary':
['mean', 'sum']})
print(grouped_df)
# Output:
# Salary
# mean sum
# Department
# Finance 61000.0 122000
# HR 52500.0 105000
# IT 70000.0 70000
2
Chapter 6
DATA CLEANING
1. Identifying and Handling Missing Data
2. Removing Duplicates
3. Data Type Conversion
4. Renaming Columns and Indexes
Identifying and Handling Missing Data
Missing data is a common issue in datasets. Missing
values can cause errors or inaccurate results during
analysis, so it’s important to identify and handle
them.
For Example:
import pandas as pd
# Sample data
data = {'Name': ['Alice', 'Bob', 'Charlie',
None],
'Age': [25, None, 30, 22]}
df = [Link](data)
2
Handling Missing Data:
For Example:
2
Removing Duplicates
Duplicates in data can lead to incorrect conclusions,
so they need to be removed. You can remove
duplicate rows using .drop_duplicates().
For Example:
# Removing duplicates
df_no_duplicates = df.drop_duplicates()
print(df_no_duplicates)
2
Data Type Conversion
Sometimes, data in a column might not have the
correct type (e.g., a column of numbers may be
stored as strings). You can convert data types using
the .astype() method.
For Example:
2
Renaming Columns and Indexes
To make your data easier to work with, you might
want to rename columns or index labels. This can be
done using the .rename() method.
For Example:
# Sample data
data = {'name': ['Alice', 'Bob'], 'age': [25,
30]}
df = [Link](data)
# Renaming columns
df_renamed = [Link](columns={'name':
'Name', 'age': 'Age'})
print(df_renamed)
2
Chapter 7
DATA VISUALIZATION
WITH PANDAS
1. Plotting Data with Pandas
2. Basic Plot Types (Line, Bar, Histogram, etc.)
3. Customizing Plots
Plotting Data with Pandas
Pandas has built-in functionality to create simple
visualizations, making it easy to plot data directly
from DataFrames. The .plot() method is the main
function used to create plots.
For Example:
import pandas as pd
import [Link] as plt
# Sample data
data = {'Year': [2018, 2019, 2020, 2021],
'Sales': [200, 300, 400, 350]}
df = [Link](data)
2
Basic Plot Types(Line, Bar, Histogram)
Pandas supports several types of plots. You can
specify the type of plot using the kind argument in
the .plot() function.
For Example:
For Example:
2
Histogram: Useful for showing the distribution of a
variable.
For Example:
# Plotting a histogram
[Link](y='Age', kind='hist', bins=5)
[Link]()
2
Customizing Plots
You can customize plots to make them more
informative by adding titles, labels, colors, and
adjusting the figure size.
For Example:
2
Chapter 8
WORKING WITH
DATES AND TIMES
1. DateTime in Pandas
2. Converting Strings to DateTime
3. DateTime Operations
Customizing Plots
You can customize plots to make them more
informative by adding titles, labels, colors, and
adjusting the figure size.
For Example:
2
DateTime in Pandas
Pandas provides powerful tools to work with dates
and times using the datetime module.
For Example:
import pandas as pd
# Sample data
data = {'Date': ['2023-01-01', '2023-02-01',
'2023-03-01']}
df = [Link](data)
2
DateTime Operations
Pandas allows you to perform various operations on
datetime data, such as extracting specific parts (e.g.,
year, month) or performing calculations (e.g.,
adding/subtracting days).
# Sample data
data = {'Date': ['2023-01-01', '2023-02-01']}
df = [Link](data)
df['Date'] = pd.to_datetime(df['Date'])
2
Example 2: Adding/Subtracting Days You can use
[Link] to add or subtract time from a date.
2
Chapter 9
INPUT/OUTPUT
OPERATIONS
1. Reading Data from CSV, Excel, and other formats
2. Writing Data to Files
3. Working with Large Datasets
Reading Data from CSV, Excel, and
Other Formats
Pandas makes it easy to load data from various
formats like CSV and Excel into DataFrames using
simple functions.
For Example :
import pandas as pd
2
Reading Excel Files: You can also read data from
Excel files using pd.read_excel(). You may need to
specify the sheet name.
For Example :
2
Writing Data to Files
Once you've worked on your data, you can save it
back to various formats like CSV, Excel, or JSON
using Pandas' to_* methods.
For Example :
For Example :
2
Working with Large Datasets
When working with large datasets, it’s important to
handle the data efficiently to avoid memory issues.
For Example :
2
Optimizing Memory Usage: You can reduce
memory usage by specifying data types when
reading the file.
For Example :
2
Chapter 9
ADVANCED TOPICS
1. Pivot Tables
2. Reshaping Data (Melt and Pivot)
3. MultiIndex DataFrames
Pivot Tables
Pivot tables are a powerful tool to summarize and
analyze data.
For Example :
import pandas as pd
# Sample data
data = {'Date': ['2023-01-01', '2023-01-01',
'2023-02-01'],
'Category': ['A', 'B', 'A'],
'Sales': [200, 150, 300]}
df = [Link](data)
2
Reshaping Data (Melt and Pivot)
Reshaping data helps in transforming the structure of
your DataFrame to make it more suitable for analysis.
For Example :
# Sample data
data = {'Date': ['2023-01-01', '2023-02-01'],
'Sales_A': [200, 300],
'Sales_B': [150, 250]}
df = [Link](data)
2
Pivot: [Link]() is used to reshape data from long
format to wide format, creating a DataFrame with
hierarchical indexing.
For Example :
# Sample data
melted_data = {'Date': ['2023-01-01', '2023-
01-01', '2023-02-01', '2023-02-01'],
'Category': ['Sales_A',
'Sales_B', 'Sales_A', 'Sales_B'],
'Sales': [200, 150, 300, 250]}
melted_df = [Link](melted_data)
2
MultiIndex DataFrames
A MultiIndex DataFrame allows you to have multiple
levels of indexing on rows and columns. This is
useful for working with hierarchical data.
For Example :
2
Akash • Python & Tech Enthusiast
@[Link]
🚀
FIL
RING SELECTING
TE
LO RO RING
EXP TA COLUMNS W
DA S
SO
PBY R
U DA TIN
RO TA G
HA SSIN
G
CO DING
NS
MI LUES
ND
VA
LUM
LIN
AD
G
G
SAV LES
CSV
CSV NG
S
FILE
DI
ING
FI
REA
PANDAS
Cheatsheet
Import Pandas
import pandas as pd
Explanation:
Pandas helps us work with tables, CSV files, and
structured data easily.
Riya 22 Mumbai 92
Aman 20 Delhi 76
Sneha 23 Bangalore 95
Rahul 21 Pune 67
Priya 22 Delhi 81
we will
CS V file
is the le s.
This xam p
ra ll e
e fo
us
import pandas as pd
students = pd.read_csv("[Link]")
print(students)
Output
Name Age City Marks
0 Akash 21 Pune 88
1 Riya 22 Mumbai 92
2 Aman 20 Delhi 76
3 Sneha 23 Bangalore 95
4 Rahul 21 Pune 67
5 Priya 22 Delhi 81
Explanation:
read_csv() loads CSV data into a DataFrame.
Quick Exploration
View First 5 Rows
print([Link]())
Output
Name Age City Marks
0 Akash 21 Pune 88
1 Riya 22 Mumbai 92
2 Aman 20 Delhi 76
3 Sneha 23 Bangalore 95
4 Rahul 21 Pune 67
Explanation:
head() shows the first rows of the dataset.
Dataset Information
Check Info
print([Link]())
Output
<class '[Link]'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 4 columns):
Name 6 non-null object
Age 6 non-null int64
City 6 non-null object
Marks 6 non-null int64
Explanation:
info() gives column names, data types, and missing
values.
Select Columns
Single Column
print(students["Name"])
Output
0 Akash
1 Riya
2 Aman
3 Sneha
4 Rahul
5 Priya
Explanation:
Use column names to select specific data.
Select Columns
Multiple Columns
print(students[["Name", "Marks"]])
Output
Name Marks
0 Akash 88
1 Riya 92
2 Aman 76
3 Sneha 95
4 Rahul 67
5 Priya 81
Explanation:
Use column names to select specific data.
Filter Rows
Students With Marks Above 80
Output
Name Age City Marks
0 Akash 21 Pune 88
1 Riya 22 Mumbai 92
3 Sneha 23 Bangalore 95
5 Priya 22 Delhi 81
Explanation:
Filtering helps us get rows matching a condition.
Multiple Conditions
Students From Pune With Marks Above 70
Output
Name Age City Marks
0 Akash 21 Pune 88
Explanation:
Use & for AND and | for OR conditions.
Sorting Data
Sort By Marks
print(students.sort_values(by="Marks", ascending=False))
Output
Name Age City Marks
3 Sneha 23 Bangalore 95
1 Riya 22 Mumbai 92
0 Akash 21 Pune 88
5 Priya 22 Delhi 81
2 Aman 20 Delhi 76
4 Rahul 21 Pune 67
Explanation:
We can create new columns easily in Pandas.
Output
Name Age City Marks Grade
0 Akash 21 Pune 88 B
1 Riya 22 Mumbai 92 A
2 Aman 20 Delhi 76 C
3 Sneha 23 Bangalore 95 A
4 Rahul 21 Pune 67 D
5 Priya 22 Delhi 81 B
Explanation:
sort_values() arranges data in ascending or descending
order.
GroupBy
Average Marks By City
print([Link]("City")["Marks"].mean())
Output
City
Bangalore 95.0
Delhi 78.5
Mumbai 92.0
Pune 77.5
Explanation:
groupby() helps summarize and analyze grouped data.
Missing Values
Check Missing Values
print([Link]().sum())
Output
Name 0
Age 0
City 0
Marks 0
Grade 0
Explanation:
isnull().sum() checks missing values in each column.
students.to_csv("updated_students.csv", index=False)
Explanation:
to_csv() saves the DataFrame into a new CSV file.
updated_students.csv
BASIC TO ADVANCE
by [Link]
1. What is NumPy?
NumPy (Numerical Python) is a Python library used to work
with numbers in the form of arrays and matrices. It helps you
perform fast mathematical and scientific computations.
1. Install NumPy
If you are using pip:
import numpy as np
Explanation:
numpy is the full library name
np is a short alias (standard practice)
We use np to access all NumPy functions
import numpy as np
print(np.__version__)
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
Explanation:
[Link]() converts a Python list into a NumPy array
arr now becomes a fast numerical array
Creates a 1D array
Similar to a list, but faster and math-friendly
2. Create 2D Array (Matrix)
arr2 = [Link]([[1, 2, 3],
[4, 5, 6]])
print(arr2)
5. Zeros Array
zeros_arr = [Link]((3, 4))
print(zeros_arr)
6. Ones Array
ones_arr = [Link]((2, 3))
print(ones_arr)
Diagonal = 1, rest = 0
Used in linear algebra
Output: (2, 3)
Means 2 rows and 3 columns
Output: 6
Total number of elements
3. Number of Dimensions
print([Link])
Output: 2
1 = 1D, 2 = 2D, 3 = 3D, etc.
5. Reshape Array
new_arr = [Link](3, 2)
print(new_arr)
Row 0, Column 1 →2
ALL NOTES ARE UPLOADED ON TELEGRAM
@[Link] – CHECK THE LINK IN BIO
AKASH • PYTHON & TECH ENTHUSIAST
@[Link]
Rows 0 to 1
Columns 1 to 2
7. Boolean Indexing
arr2 = [Link]([5, 10, 15, 20, 25])
print(arr2[arr2 > 15])
1. Element-wise Addition
import numpy as np
a = [Link]([1, 2, 3])
b = [Link]([10, 20, 30])
print(a + b)
2. Subtraction
print(b - a)
3. Multiplication
print(a * b)
4. Division
print(b / a)
6. Comparison Operations
print(a > 2)
7. Aggregation Functions
print([Link]())
print([Link]())
print([Link]())
print([Link]())
sum() →
total
mean() →
average
max() →
largest
min() →
smallest
axis=0 → column-wise
axis=1 → row-wise
2. 2D Array + 1D Array
matrix = [Link]([[1, 2, 3],
[4, 5, 6]])
add_arr = [Link]([10, 20, 30])
print(matrix + add_arr)
Mean →
average
Median →
middle value
Std →
spread of data
Var →
square of std
1. Sorting an Array
import numpy as np
arr = [Link]([40, 10, 30, 20])
print([Link](arr))
5. Unique Values
arr = [Link]([1, 2, 2, 3, 3, 3, 4])
print([Link](arr))
3. Concatenate
print([Link]((a, b)))
4. Split Array
arr = [Link]([10, 20, 30, 40, 50, 60])
print([Link](arr, 3))
2. Random Integers
print([Link](1, 10, size=5))
3. Random 2D Array
print([Link](3, 3))
6. Permutation
arr = [Link]([1, 2, 3, 4])
print([Link](arr))
2. Matrix Multiplication
A = [Link]([[1, 2],
[3, 4]])
B = [Link]([[5, 6],
[7, 8]])
print([Link](A, B))
4. Inverse of Matrix
inv_A = [Link](A)
print(inv_A)
5. Determinant
print([Link](A))
2. Boolean Masking
data = [Link]([5, 12, 18, 25, 30])
mask = data > 15
print(mask)
print(data[mask])
4. Conditional Update
arr2 = [Link]([1, 2, 3, 4, 5])
arr2[arr2 % 2 == 0] = 0
print(arr2)
If score ≥ 50 → Pass
Else → Fail
for i in range(len(arr)):
arr[i] = arr[i] + 5
Good (fast):
arr = arr + 5
MATPLOTLIB
Cheatsheet
Import Matplotlib
Explanation:
Matplotlib helps us create charts and graphs to visualize
data.
Sample Data
Data we'll use for all examples
Explanation:
This is the data we will use for all examples.
Line Plot
Basic Line Chart
[Link](months, sales)
[Link]()
Output
Explanation:
plot() draws a line connecting the data points.
Customize Line
Color, Style & Markers
Output
Explanation:
Use color, linestyle, and marker to style the line.
Output
Explanation:
Labels and titles make charts easier to understand.
Bar Chart
Vertical Bars
Output
Explanation:
bar() shows values as rectangular bars.
Histogram
Distribution of Data
Output
Explanation:
hist() shows how data is distributed across ranges
(bins).
Scatter Plot
Relationship Between Values
Output
Explanation:
scatter() shows the relationship between two variables.
Pie Chart
Show Proportions
Output
Explanation:
pie() shows parts of a whole as percentages.
Multiple Lines
Compare Two Lines
Output
Explanation:
Plot multiple lines to compare different data sets.
Subplots
Multiple Charts Together
[Link](1, 2, 1)
[Link](months, sales)
[Link](1, 2, 2)
[Link](months, sales)
[Link]()
Output
Explanation:
subplot() places several charts in one figure.
[Link]("ggplot")
[Link](months, sales)
[Link](True)
[Link]()
Output
Explanation:
Styles and grids make charts cleaner and easier to read.
Figure Size
Resize the Chart
[Link](figsize=(8, 4))
[Link](months, sales)
[Link]()
Output
Explanation:
figsize sets the width and height of the figure.
Save Figure
Save Your Plot
[Link](months, sales)
[Link]("sales_chart.png")
Explanation:
savefig() saves the chart as an image file.