0% found this document useful (0 votes)
9 views12 pages

Understanding Python Loops and Functions

The document provides an overview of loops in Python, specifically focusing on for and while loops, along with examples of their usage. It also explains the concept of functions, their benefits, and provides a comparison between Pandas Series and DataFrame, as well as a discussion on indexing in Pandas. Additionally, it covers the differences between NumPy arrays and Python lists, key functionalities of Pandas for data manipulation, and techniques for data cleaning.

Uploaded by

kuchbhi323232
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views12 pages

Understanding Python Loops and Functions

The document provides an overview of loops in Python, specifically focusing on for and while loops, along with examples of their usage. It also explains the concept of functions, their benefits, and provides a comparison between Pandas Series and DataFrame, as well as a discussion on indexing in Pandas. Additionally, it covers the differences between NumPy arrays and Python lists, key functionalities of Pandas for data manipulation, and techniques for data cleaning.

Uploaded by

kuchbhi323232
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

How Loops Work in Python?

(For Loop Example)

Loops in Python are used to execute a block of code mul ple mes. Python provides two
types of loops:

1. For Loop – Used to iterate over a sequence (list, tuple, dic onary, string, etc.).

2. While Loop – Runs as long as a condi on is true.

For Loop in Python

 The for loop is used when you want to iterate over a known sequence (like a list or
range).

 Syntax:

for variable in sequence:

# Code to execute

Example 1: Using a For Loop with range()

for i in range(1, 6): # Iterates from 1 to 5

print(i)

Output:

Example 2: Itera ng Over a List

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print(fruit)

Output:

apple

banana

cherry
While Loop in Python

A while loop in Python is used to execute a block of code as long as a specified condi on is
true. It is useful when the number of itera ons is not known beforehand.

Syntax of a While Loop

while condi on:

# Code to execute

 The loop con nues execu ng as long as the condi on is True.

 The condi on is checked before each itera on.

Example 1: Basic While Loop

x=1

while x <= 5:

print(x)

x += 1 # Increment x to avoid infinite loop

Output:

What is a Func on?

A func on in Python is a block of reusable code that performs a specific task. Func ons
allow us to break down complex problems into smaller, manageable parts, making our code
more organized and efficient.

Why Use Func ons?

1. Code Reusability – Write once, use mul ple mes.


2. Improves Readability – Makes code cleaner and more structured.

3. Reduces Redundancy – Avoids repea ng the same code.

4. Easier Debugging – Isolates errors to specific func ons.

5. Encapsula on – Groups related logic together.

Syntax of a Func on

def func on_name(parameters):

"""Docstring explaining the func on"""

# Func on body

return value # (op onal)

Example: A Simple Func on

def greet(name):

return f"Hello, {name}!"

print(greet("Alice"))

Output:

Hello, Alice!

Here’s a table comparing Pandas Series and Pandas DataFrame with examples:

Feature Pandas Series Pandas DataFrame

A two-dimensional table with rows and


Defini on A one-dimensional labeled array
columns

Single column of data with an


Structure Mul ple columns with an index
index

Can hold integers, floats, strings, Each column can have a different data
Data Type
etc. type
Feature Pandas Series Pandas DataFrame

Indexing Has a single index for values Has both row index and column labels

Shape (n,) → Single column with n rows (n, m) → n rows and m columns

Example
```python ```python
(Code)

import pandas as pd import pandas as pd

data = {"Name": ["Alice", "Bob"],


data = [10, 20, 30]
"Age": [25, 30]}

series = [Link](data, index=["a",


df = [Link](data)
"b", "c"])

print(series) print(df)

Example
``` ```
(Output)

a 10 Name Age

b 20 0 Alice 25

c 30 1 Bob 30

dtype: int64

- Works like a dic onary (index →


Usage - Similar to a spreadsheet or SQL table
value)

- Used for single-column


- Used for complex datasets
computa ons

- Vectorized opera ons (e.g., series


Opera ons - Data analysis, filtering, merging, etc.
+ 10)
3. Role of Indexing in Pandas & Its Importance

What is Indexing?

 Indexing in Pandas helps in iden fying and accessing data efficiently.

 Every row in a Series or DataFrame has an index (default is 0, 1, 2,...).

Why is Indexing Important?

Faster Data Access – Locate rows quickly using labels.


Data Selec on – Extract rows or columns easily.
Data Manipula on – Helps in filtering, grouping, and merging datasets.

Types of Indexing in Pandas

1. Label-based Indexing (loc[])

 Select rows/columns using labels.

df = [Link]({"Name": ["Alice", "Bob"], "Age": [25, 30]}, index=["A", "B"])

print([Link]["A"]) # Access row with index 'A'

Output:

Name Alice

Age 25

Name: A, dtype: object

2. Posi on-based Indexing (iloc[])

 Select rows/columns using posi on (integer index).

print([Link][1]) # Access second row

Output:

Name Bob

Age 30

Name: B, dtype: object

3. Se ng a Custom Index

 Change the index to a column value.

df.set_index("Name", inplace=True)
print(df)

NumPy Arrays vs. Python Lists (9 Marks)

NumPy (Numerical Python) provides arrays, which are highly efficient for numerical
compu ng. A NumPy array (ndarray) is a fixed-size, mul -dimensional container for
elements of the same data type, while Python lists can hold mixed data types.

Differences Between NumPy Arrays and Python Lists

Feature NumPy Array (ndarray) Python List

Homogeneous (all elements must be Heterogeneous (can have


Data Type
the same type) mixed types)

Faster (Op mized for numerical Slower (Python's built-in


Performance
opera ons) dynamic type checking)

Uses less memory (stored as a Uses more memory (stores


Memory Efficiency
con guous block) references)

Mathema cal Supports element-wise opera ons (arr Requires explicit loops (for or
Opera ons + 1) map())

Supports vectorized opera ons, Lacks built-in vectorized


Func onality
broadcas ng, etc. opera ons

Mul -Dimensional Supports 1D, 2D, and mul -


Only supports 1D nested lists
Support dimensional arrays

NumPy provides many mathema cal Lists require manual itera on


Built-in Methods
func ons (mean(), sum(), etc.) or map() func ons

Example 1: Crea ng a NumPy Array vs. Python List

import numpy as np

# Python List

py_list = [1, 2, 3, 4, 5]
# NumPy Array

np_array = [Link]([1, 2, 3, 4, 5])

print("Python List:", py_list)

print("NumPy Array:", np_array)

Output:

Python List: [1, 2, 3, 4, 5]

NumPy Array: [1 2 3 4 5]

Key Func onali es of Pandas for Data Manipula on and Analysis

Pandas is a powerful Python library for data manipula on and analysis. It provides flexible
data structures (Series & DataFrame) and numerous built-in func ons for handling
structured data efficiently.

1. Crea ng a DataFrame

A Pandas DataFrame is a table-like structure where data is stored in rows and columns.

import pandas as pd

# Crea ng a DataFrame

data = {

"Name": ["Alice", "Bob", "Charlie", "David"],

"Age": [25, 30, 35, 40],

"City": ["New York", "London", "Paris", "Berlin"],

"Salary": [50000, 60000, 55000, 70000]

}
df = [Link](data)

print(df)

Output:

Name Age City Salary

0 Alice 25 New York 50000

1 Bob 30 London 60000

2 Charlie 35 Paris 55000

3 David 40 Berlin 70000

Pandas makes it easy to store and manipulate structured data!

2. Filtering Data

Filtering allows selec ng specific rows based on condi ons.

python

CopyEdit

# Filter rows where Age > 30

filtered_df = df[df["Age"] > 30]

print(filtered_df)

Output:

Name Age City Salary

2 Charlie 35 Paris 55000

3 David 40 Berlin 70000

Efficiently extract relevant rows using condi ons!

3. Sor ng Data

Sor ng helps in organizing data based on column values.

# Sor ng by Salary in descending order

sorted_df = df.sort_values(by="Salary", ascending=False)


print(sorted_df)

Output:

Name Age City Salary

3 David 40 Berlin 70000

1 Bob 30 London 60000

2 Charlie 35 Paris 55000

0 Alice 25 New York 50000

Sor ng is useful for ranking and analyzing trends!

4. Aggrega ng Data

Aggrega on helps to compute summary sta s cs like sum, mean, min, and max.

# Calculate average salary

average_salary = df["Salary"].mean()

print("Average Salary:", average_salary)

Output:

Average Salary: 58750.0

Quickly compute useful sta s cs for analysis!

Data Cleaning Techniques in Pandas

Data cleaning is a crucial step in data preprocessing to ensure accuracy, consistency, and
completeness of data. Pandas provides various func ons to handle missing values, remove
duplicates, and fix inconsistent forma ng.

1. Handling Missing Data (NaN values)


Missing values can affect analysis and model performance, so they need to be handled
carefully.

a) Detec ng Missing Values

import pandas as pd

import numpy as np

# Crea ng a DataFrame with missing values

data = {

"Name": ["Alice", "Bob", "Charlie", "David"],

"Age": [25, [Link], 35, 40],

"City": ["New York", "London", [Link], "Berlin"],

"Salary": [50000, 60000, 55000, [Link]]

df = [Link](data)

print(df)

Output:

Name Age City Salary

0 Alice 25.0 New York 50000.0

1 Bob NaN London 60000.0

2 Charlie 35.0 NaN 55000.0

3 David 40.0 Berlin NaN

NaN represents missing values in Pandas.

b) Removing Missing Values (dropna())

# Remove rows with any missing values

df_cleaned = [Link]()

print(df_cleaned)
Use dropna() to remove rows/columns with missing values.

c) Filling Missing Values (fillna())

# Fill missing Age with the average Age

df["Age"].fillna(df["Age"].mean(), inplace=True)

# Fill missing Salary with a fixed value (e.g., 50000)

df["Salary"].fillna(50000, inplace=True)

# Fill missing City with 'Unknown'

df["City"].fillna("Unknown", inplace=True)

print(df)

Use fillna() to replace missing values with a mean, median, or custom value.

2. Handling Duplicate Data

Duplicate records can cause biased analysis.

a) Detec ng Duplicates

# Crea ng a DataFrame with duplicate entries

data = {

"Name": ["Alice", "Bob", "Charlie", "Alice"],

"Age": [25, 30, 35, 25],

"City": ["New York", "London", "Paris", "New York"],

df = [Link](data)

# Check for duplicates


print([Link]())

Output:

0 False

1 False

2 False

3 True

dtype: bool

duplicated() iden fies duplicate rows.

b) Removing Duplicates (drop_duplicates())

# Remove duplicate rows

df_no_duplicates = df.drop_duplicates()

print(df_no_duplicates)

Use drop_duplicates() to remove redundant data.

3. Handling Inconsistent Forma ng

Data might have inconsistent capitaliza on, extra spaces, or incorrect formats.

a) Fixing Case Inconsistencies

# Fixing inconsistent capitaliza on in 'City' column

df["City"] = df["City"].[Link]() # Convert to lowercase

print(df)

Ensure uniform text case using .[Link]() or .[Link]().

You might also like