0% found this document useful (0 votes)
10 views25 pages

Portfolio Optimization with Python Code

The document outlines a step-by-step approach to portfolio optimization using Python, focusing on five stock tickers. It explains how to gather stock data, calculate daily returns, annualized mean and standard deviation, and the Sharpe ratio, ultimately determining optimal weights for maximizing returns while minimizing risk. The logic is presented through relatable analogies, making it easier to remember the process for future reference.

Uploaded by

Prerna Gupta
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)
10 views25 pages

Portfolio Optimization with Python Code

The document outlines a step-by-step approach to portfolio optimization using Python, focusing on five stock tickers. It explains how to gather stock data, calculate daily returns, annualized mean and standard deviation, and the Sharpe ratio, ultimately determining optimal weights for maximizing returns while minimizing risk. The logic is presented through relatable analogies, making it easier to remember the process for future reference.

Uploaded by

Prerna Gupta
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

Errors: If pd.read_html fails, you might get empty tables.

Let me know if you see 


issues.

What to Do Next

1. Run the Code: Copy into a Jupyter cell and execute.

2. Check Output: Verify the CSV files are created.

3. Report Back: Let me know if it works or if you need adjustments.

Since it’s 09:22 PM IST on October 22, 2025, you can test this tonight. Once
confirmed, we can move to the next question or refine this further!

explain me the logic so i can remember tomorrow

Sure! Let’s break down the logic of the code for Question 2 in a simple and memorable
way so you can recall it tomorrow. Since the code scrapes financial data from
Moneycontrol URLs, drops the last column, and exports each table to a separate CSV
file, I’ll explain each part step by step. I’ll use analogies and key points to make it stick.
The current time is 09:25 PM IST on October 22, 2025, so we’ll keep this concise for
your review tomorrow!

Overall Goal

Imagine you’re a librarian collecting financial "books" (tables) from different company
"shelves" (websites) and organizing them into separate "folders" (CSV files) after
removing the last "page" (column) you don’t need. The code does this systematically
for 5 companies, each with 3 types of financial statements.

Step-by-Step Logic
1. Setting Up the Library (Imports and URLs)

Code: import pandas as pd

Logic: You’re bringing in a tool ( pandas ) to help you read and organize tables
from websites, like hiring a librarian.

Code: url_fin_financials = [...]

Logic: This is your list of "shelves" (15 URLs) where the financial "books" are
stored. Each URL points to a company’s balance sheet, profit-loss, or cash-
flow page for 5 companies (Larsen & Toubro, Power Grid, Axis Bank, Tata Steel, 
Hindalco).

Memorable Tip: Think of it as a map with 15 stops, 3 for each of 5 companies.

2. Collecting the Books (Loop and read_html )

Code:

python

fin_financials = []
for x in url_fin_financials:
fin_result = pd.read_html(x, header=0, skiprows=[1, 2])
fin_financials.extend(fin_result)

Logic:

fin_financials = [] : Start with an empty "bookcase" to store all tables.

for x in url_fin_financials : Visit each "shelf" (URL) one by one.

pd.read_html(x, header=0, skiprows=[1, 2]) : This "reads" the tables


from the webpage. header=0 makes the first row the column names, and
skiprows=[1, 2] skips extra header rows (like skipping the title page of a

book).

fin_financials.extend(fin_result) : Adds all "books" (tables) from that

shelf to the bookcase. Since read_html might find multiple tables per URL,
extend unpacks them and adds each one separately (unlike append , which

would add the whole stack as one item).

Memorable Tip: Picture a librarian unpacking a box of books and placing each
one on the shelf, one URL at a time. After 15 URLs, you have 15 (or more) books
if each URL has one table.

3. Trimming the Last Page (Dropping the Last Column)

Code:

python

for i in range(len(fin_financials)):
fin_financials[i] = fin_financials[i].iloc[:, 0:5]

Logic:
range(len(fin_financials)) : Go through each "book" (table) in the 
bookcase.

fin_financials[i].iloc[:, 0:5] : This "trims" each table by keeping only


the first 5 columns (indices 0 to 4) and dropping the last one (index 5).
iloc is like using a ruler to cut pages, and 0:5 means "from the first page

to the fifth."

Memorable Tip: Think of removing the last page of each book because it’s not
needed, leaving you with a neater 5-page story per table.

4. Organizing into Folders (Exporting to CSV)

Code:

python

companies = ['LT', 'PGC', 'AB16', 'TIS', 'HI']


statements = ['balance-sheet', 'profit-loss', 'cash-flow']
for i in range(len(fin_financials)):
company_idx = i / 3
statement_idx = i % 3
company_code = companies[int(company_idx)]
statement_type = statements[int(statement_idx)]
filename = company_code + "_" + statement_type + ".csv"
fin_financials[i].to_csv(filename, index=False)
print("Saved: " + filename)

Logic:

companies and statements : These are your "labels" for the 5 companies

and 3 statement types.

i / 3 and i % 3 : These are math tricks to figure out which company and

statement type each table belongs to. Since there are 3 statements per
company, dividing i by 3 gives the company number (0 to 4), and the
remainder ( % 3 ) gives the statement number (0 to 2).

company_code = companies[int(company_idx)] : Picks the company code

(e.g., ‘LT’ for index 0).

statement_type = statements[int(statement_idx)] : Picks the statement

type (e.g., ‘balance-sheet’ for index 0).

filename = company_code + "_" + statement_type + ".csv" : Builds the

folder name by joining the company and statement with an underscore


(e.g., LT_balance-[Link] ). 

fin_financials[i].to_csv(filename, index=False) : Saves each "book"

as a separate "folder" (CSV file) in your notebook’s directory, without extra


row numbers ( index=False ).

print("Saved: " + filename) : Tells you which folder was created.

Memorable Tip: Imagine labeling each book with its company and type (e.g.,
“LT Balance Sheet”) and filing it in a cabinet. The math ( / 3 and % 3 ) is like a
filing system: every 3 books, you move to the next company.

Key Points to Remember Tomorrow

1. Flow:

Start with a list of URLs (shelves).

Collect tables (books) using read_html and extend .

Trim each table (drop last column).

Save each table as a separate CSV (folder) with a name based on company and
statement.

2. extend vs. append :

extend adds each item (table) separately, like stacking books one by one.

append would add the whole stack as one big box, which you don’t want.

3. Index Math:

i / 3 → Company number (e.g., 0 for LT, 1 for PGC).

i % 3 → Statement number (e.g., 0 for balance-sheet, 1 for profit-loss).

This works because you have 3 statements per company.

4. File Naming:

Combine company code and statement type with + (e.g., LT + "_" +


balance-sheet + ".csv" ).

Quick Recap Analogy

You’re a librarian:

URLs: A map to 15 shelves.


read_html: Grabs all books from each shelf. 

extend: Places each book on the shelf individually.

iloc[:, 0:5]: Cuts off the last page of each book.

Loop with / 3 and % 3: Labels each book with its company and type.

to_csv: Files each book in its own folder.

Tomorrow’s Plan

Run the Code: Copy it into Jupyter and execute.

Check Files: Look for 15 CSV files in your notebook folder.

Troubleshoot: If no files appear, check the URLs or ensure pandas is working.

Ask: If stuck, recall this logic and ask me to refine it!

It’s 09:30 PM IST now, so get some rest. You’ll nail this tomorrow! Let me know if you
need a quick review then.

do the same for this:import yfinance as yf


import pandas as pd
import numpy as np
import pypfopt as pf
import [Link] as plt
import empyrical as ep
symbols=["BAJAJ-
[Link]","[Link]","[Link]","[Link]","[Link]"]
portfolio_stk=[Link](symbols, start="2021-01-01", end="2024-10-
26")
portfolio_stk= portfolio_stk["Close"]
portfolio_stk
daily_returns = portfolio_stk.pct_change().dropna()
portfolio_mean = daily_returns.mean() * 252
print("Portfolio Mean (Annualized Return):")
print(portfolio_mean)
print("-----------------------------------------------------------")
print("\n")
portfolio_std = daily_returns.std() * [Link](252) # Annualized by
multiplying by sqrt(252)
print("Portfolio Standard Deviation (Annualized Risk):") 
print(portfolio_std)
print("-----------------------------------------------------------")
print("\n")
risk_free_rate = 0.04
sharpe_ratio = (portfolio_mean - risk_free_rate) / portfolio_std
print("Sharpe Ratio:")
print(sharpe_ratio)
print("-----------------------------------------------------------")
print("\n")
expected_returns =
pf.expected_returns.mean_historical_return(portfolio_stk)
cov_matrix = pf.risk_models.sample_cov(portfolio_stk)
ef = pf.efficient_frontier.EfficientFrontier(expected_returns, cov_matrix)
optimal_weights = ef.max_sharpe() # Optimize for maximum Sharpe ratio
cleaned_weights = ef.clean_weights() # Round weights for readability
print("Optimal Weights: ")
print(cleaned_weights)
print("-------------------------------------------------------------")
print("\n")
optimum_mean = ef.portfolio_performance(verbose=True) # Returns
(mean, std, sharpe)
print("Optimum Portfolio Performance (Mean, Std, Sharpe):")
print(optimum_mean)
print("-------------------------------------------------------------")
print("\n")

Great! Let’s break down the logic of the code for Question 1 (portfolio optimization) in
a simple and memorable way, similar to how we did for Question 2. This code
calculates the portfolio mean, standard deviation, Sharpe ratio, optimum portfolio
mean, standard deviation, and optimal weights for five stock tickers using historical
data. I’ll use analogies and key points to help you remember it tomorrow. The current
time is 09:54 PM IST on October 22, 2025, so we’ll keep this concise for your review.

Overall Goal

Imagine you’re a financial advisor building an investment "portfolio basket" for 5


stocks. You’re analyzing their past performance (like checking their growth records),
calculating their average gains and risks, finding the best mix to maximize returns for 
the least risk, and reporting the results. The code does this step by step.

Step-by-Step Logic
1. Gathering the Ingredients (Imports and Data)

Code:

python

import yfinance as yf
import pandas as pd
import numpy as np
import pypfopt as pf
import empyrical as ep

Logic: You’re collecting tools from your "finance toolbox":

yfinance : Fetches stock data from the internet (like a data collector).

pandas : Organizes the data into tables (your record book).

numpy : Helps with math calculations (your calculator).

pypfopt : Optimizes the portfolio (your strategy planner).

empyrical : Calculates financial metrics (your performance analyst).

Code:

python

symbols = ["[Link]", "[Link]", "[Link]", "[Link]"


portfolio_stk = [Link](symbols, start="2021-01-01", end="2024-
portfolio_stk = portfolio_stk["Close"]

 

Logic:

symbols : Your list of 5 stocks to put in the basket.

[Link] : Goes online to grab the daily closing prices for these stocks

from January 1, 2021, to October 26, 2024.

portfolio_stk["Close"] : Keeps only the closing prices (the final value

each day), like focusing on the day’s sales total.


Memorable Tip: Think of filling a basket with 5 fruits (stocks) and checking 
their daily market prices.

2. Measuring Daily Growth (Daily Returns)

Code:

python

daily_returns = portfolio_stk.pct_change().dropna()

Logic:

pct_change() : Calculates the daily percentage change (growth or loss) for

each stock, like measuring how much each fruit’s price changed day to day.

.dropna() : Removes the first day (where change can’t be calculated), like

throwing out a spoiled fruit.

Memorable Tip: Picture tracking how much each fruit’s price jumps or drops
daily.

3. Calculating Average Gains (Portfolio Mean)

Code:

python

portfolio_mean = daily_returns.mean() * 252


print("Portfolio Mean (Annualized Return):")
print(portfolio_mean)
print("-----------------------------------------------------------")
print("\n")

 

Logic:

daily_returns.mean() : Averages the daily growth across all days for each

stock, like finding the average daily price increase.

* 252 : Multiplies by 252 (trading days in a year) to estimate the yearly gain,

turning a daily snack into a yearly feast.

print : Shows the annualized return for each stock.

Memorable Tip: Think of averaging the daily growth of each fruit and scaling it
up to a year’s worth.
4. Measuring Risk (Portfolio Standard Deviation) 

Code:

python

portfolio_std = daily_returns.std() * [Link](252)


print("Portfolio Standard Deviation (Annualized Risk):")
print(portfolio_std)
print("-----------------------------------------------------------")
print("\n")

 

Logic:

daily_returns.std() : Measures how much the daily growth varies (risk),


like checking how wildly each fruit’s price swings.

* [Link](252) : Annualizes the risk by multiplying by the square root of


252, adjusting for a full year.

print : Displays the annualized risk for each stock.

Memorable Tip: Imagine measuring how shaky each fruit’s price is and scaling
that shakiness to a year.

5. Evaluating Performance (Sharpe Ratio)

Code:

python

risk_free_rate = 0.04
sharpe_ratio = (portfolio_mean - risk_free_rate) / portfolio_std
print("Sharpe Ratio:")
print(sharpe_ratio)
print("-----------------------------------------------------------")
print("\n")

 

Logic:

risk_free_rate = 0.04 : Sets a safe return (e.g., 4% from a bank), like a


steady baseline.

(portfolio_mean - risk_free_rate) / portfolio_std : Compares the


extra gain (above the safe return) to the risk, giving a score (higher is
better). 

print : Shows the Sharpe ratio for each stock.

Memorable Tip: Think of calculating how much more you earn per unit of risk
compared to just saving money.

6. Finding the Best Mix (Optimal Weights)

Code:

python

expected_returns = pf.expected_returns.mean_historical_return(portfoli
cov_matrix = pf.risk_models.sample_cov(portfolio_stk)
ef = [Link](expected_returns, cov_matrix)
optimal_weights = ef.max_sharpe()
cleaned_weights = ef.clean_weights()
print("Optimal Weights: ")
print(cleaned_weights)
print("-------------------------------------------------------------")
print("\n")

 

Logic:

expected_returns : Estimates future gains based on past averages, like


predicting next year’s fruit yield.

cov_matrix : Measures how the stocks move together (e.g., if one fruit’s

price rises, do others?), like checking teamwork.

ef = [Link](...) : Sets up a "mixing machine" using these

predictions and teamwork data.

optimal_weights = ef.max_sharpe() : Finds the best mix (weights) to

maximize the Sharpe ratio, like balancing the basket for the best taste-to-
risk ratio.

cleaned_weights : Rounds the mix percentages for clarity.

print : Shows how much of each stock to hold (sums to 100%).

Memorable Tip: Picture adjusting the fruit mix to get the sweetest basket with
the least spoilage risk.

7. Checking the Best Basket (Optimum Performance)

Code:
python 

optimum_mean = ef.portfolio_performance(verbose=True)
print("Optimum Portfolio Performance (Mean, Std, Sharpe):")
print(optimum_mean)
print("-------------------------------------------------------------")
print("\n")

 

Logic:

ef.portfolio_performance(verbose=True) : Calculates the yearly gain,

risk, and Sharpe ratio for the best mix, like tasting the final basket.

print : Shows the optimum mean (gain), standard deviation (risk), and
Sharpe ratio.

Memorable Tip: Think of checking the final basket’s yield, shakiness, and
value-for-risk score.

Key Points to Remember Tomorrow

1. Flow:

Gather stock prices (basket ingredients).

Measure daily growth (returns).

Calculate average gain (mean) and risk (std) for a year.

Score performance (Sharpe ratio).

Find the best mix (optimal weights).

Check the best basket’s stats (optimum performance).

2. Tools:

yfinance : Fetches data.

pandas : Organizes it.

numpy : Does math.

pypfopt : Optimizes.

empyrical : Analyzes.

3. Math Tricks:
* 252 : Turns daily to yearly gain. 

* [Link](252) : Turns daily to yearly risk.

(mean - risk_free) / std : Sharpe ratio formula.

4. Optimization:

Uses past data to predict and balance for the best return-risk mix.

Quick Recap Analogy

You’re a fruit vendor:

Imports: Gather your tools (data collector, organizer, calculator, planner).

Download: Fill your basket with 5 fruits’ prices.

Returns: Check daily price changes.

Mean/Std: Average the growth and measure price swings for a year.

Sharpe: Compare gains to a safe bet (bank).

Weights: Mix fruits for the best taste-risk balance.

Optimum: Taste the final mix’s yield, risk, and value.

Tomorrow’s Plan

Run the Code: Copy into Jupyter and execute.

Check Output: Look for mean, std, Sharpe, weights, and optimum stats.

Troubleshoot: If errors (e.g., data issues), recall the flow and ask me.

Adjust: Confirm symbols and end date if needed.

It’s 09:58 PM IST now, so rest up! You’ll remember this tomorrow. Let me know if you
need a quick refresher then!

for this tooo: #3


import json
import requests
import pandas as pd
codes = ["104562", "104568", "104573", "104578", "104584"]
for code in codes:
url = "[Link] + code
mf_detail = [Link](url).json()

if 'data' not in mf_detail or not mf_detail['data']:
print("No data available for code: " + code)
print("--------------------------------------------------")
continue

mf = [Link]([mf_detail['meta']])
mf_nav = [Link](mf_detail['data'])

if 'date' in mf_nav.columns and 'nav' in mf_nav.columns:


mf_nav['date'] = pd.to_datetime(mf_nav['date'], format='%d-%m-
%Y')
mf_nav['nav'] = mf_nav['nav'].astype(float)
for col in [Link]:
mf_nav[col] = [Link][0, col]
mf_nav.to_csv(code + ".csv", index=False)
print("Saved " + code)

# Calculate and print mean and standard deviation


nav_mean = mf_nav['nav'].mean()
nav_std = mf_nav['nav'].std()
print("Code: " + code)
print("Mean NAV: " + str(round(nav_mean, 4)))
print("Standard Deviation NAV: " + str(round(nav_std, 4)))
print("--------------------------------------------------")
else:
print("Required columns missing for code: " + code)

Awesome! Let’s break down the logic of the code for Question 3 in a simple and
memorable way, just like we did for the previous questions. This code fetches mutual
fund NAV (Net Asset Value) data for five codes, processes it, saves it to CSV files, and
calculates the mean and standard deviation of the NAV. I’ll use analogies and key
points to help you recall it tomorrow. The current time is 10:03 PM IST on October 22,
2025, so we’ll keep this concise for your review.

Overall Goal
Imagine you’re a treasure hunter collecting daily "gold value" (NAV) reports for 5 
mutual funds from an online "vault" (API), organizing them into "chests" (CSV files),
and figuring out the average value and how much it fluctuates. The code does this step
by step for the codes ["104562", "104568", "104573", "104578", "104584"] .

Step-by-Step Logic
1. Gathering the Tools (Imports)

Code:

python

import json
import requests
import pandas as pd

Logic:

json : Helps read the "treasure map" (data in JSON format) from the vault.

requests : Sends a request to unlock the vault and get the data.

pandas : Organizes the treasure into tables (your record book).

Memorable Tip: Think of equipping yourself with a map reader, a key, and a
ledger.

2. Listing the Treasures (Codes)

Code:

python

codes = ["104562", "104568", "104573", "104578", "104584"]

Logic: This is your list of 5 "treasure chests" (mutual fund codes) to explore.

Memorable Tip: Picture 5 locked vaults, each with a unique code.

3. Unlocking the Vault (Loop and API Call)

Code:

python

for code in codes:
url = "[Link] + code
mf_detail = [Link](url).json()

Logic:

for code in codes : Visit each vault one by one.

url = "[Link] + code : Builds the web address by

adding the code to the base URL, like entering the vault’s location.

[Link](url).json() : Unlocks the vault and reads the treasure data

(in JSON format).

Memorable Tip: Imagine traveling to each vault, unlocking it with the code, and
peeking inside.

4. Checking the Loot (Data Validation)

Code:

python

if 'data' not in mf_detail or not mf_detail['data']:


print("No data available for code: " + code)
print("--------------------------------------------------")
continue

Logic:

Checks if the vault has treasure ( 'data' key exists and isn’t empty).

If empty, prints a warning and skips to the next vault ( continue ).

Memorable Tip: Think of checking if the vault is empty—move on if there’s no


gold!

5. Organizing the Treasure (DataFrames)

Code:

python

mf = [Link]([mf_detail['meta']])
mf_nav = [Link](mf_detail['data'])

Logic:
mf_detail['meta'] : Contains fund details (e.g., name), turned into a table 
( mf ) with one row.

mf_detail['data'] : Contains the NAV history (dates and values), turned


into a table ( mf_nav ).

Memorable Tip: Picture sorting the vault’s gold info (meta) into a small box and
the daily gold values into a big ledger.

6. Polishing the Gold (Data Cleaning)

Code:

python

if 'date' in mf_nav.columns and 'nav' in mf_nav.columns:


mf_nav['date'] = pd.to_datetime(mf_nav['date'], format='%d-%m-%Y')
mf_nav['nav'] = mf_nav['nav'].astype(float)
for col in [Link]:
mf_nav[col] = [Link][0, col]

 

Logic:

Checks if date and nav columns exist.

pd.to_datetime(...) : Converts date strings (e.g., "01-01-2020") to a

proper date format, like setting a calendar.

mf_nav['nav'].astype(float) : Turns NAV values into numbers (e.g.,

"10.5" to 10.5) for calculations.

for col in [Link] : Adds meta details (e.g., fund name) to each row
of mf_nav .

Memorable Tip: Think of cleaning and dating the gold coins, then stamping
each with the vault’s name.

7. Storing the Chest (Exporting to CSV)

Code:

python

mf_nav.to_csv(code + ".csv", index=False)


print("Saved " + code)
Logic: 

to_csv(code + ".csv", index=False) : Saves the polished NAV data as a

CSV file named with the code (e.g., [Link] ), without extra row
numbers.

print("Saved " + code) : Confirms the chest is stored.

Memorable Tip: Imagine locking the gold ledger in a chest labeled with the
vault code.

8. Analyzing the Treasure (Mean and Standard Deviation)

Code:

python

nav_mean = mf_nav['nav'].mean()
nav_std = mf_nav['nav'].std()
print("Code: " + code)
print("Mean NAV: " + str(round(nav_mean, 4)))
print("Standard Deviation NAV: " + str(round(nav_std, 4)))
print("--------------------------------------------------")

Logic:

nav_mean = mf_nav['nav'].mean() : Averages all NAV values, like finding

the average gold value.

nav_std = mf_nav['nav'].std() : Measures how much the NAV varies, like

checking gold value stability.

print : Shows the code, mean NAV, and standard deviation, rounded to 4

decimals.

Memorable Tip: Think of calculating the average gold value and how much it
jiggles day to day.

9. Handling Missing Treasure (Error Check)

Code:

python

else:
print("Required columns missing for code: " + code)
Logic: If date or nav columns are missing, prints an error and skips 
calculations.

Memorable Tip: If the vault’s ledger lacks dates or values, note it and move on.

Key Points to Remember Tomorrow

1. Flow:

List 5 vault codes.

Visit each vault, fetch data.

Check for data, organize into tables.

Clean dates and values, add details.

Save each as a CSV chest.

Calculate mean and std of NAV.

2. Tools:

requests : Unlocks the vault.

json : Reads the map.

pandas : Organizes the treasure.

3. Data Tricks:

to_datetime : Sets the calendar.

astype(float) : Turns text to numbers.

mean() and std() : Average and variation.

4. Loop Logic:

One code at a time, process and save.

Quick Recap Analogy

You’re a treasure hunter:

Imports: Grab your tools (map reader, key, ledger).

Codes: List 5 vaults to explore.

Loop: Visit each vault, unlock with the code.

Check: Ensure there’s gold, skip if empty.


Organize: Sort meta and NAV into tables. 

Clean: Date and number the gold, add vault info.

Save: Lock in a chest (CSV) per vault.

Analyze: Average the gold and check its wobble.

Tomorrow’s Plan

Run the Code: Copy into Jupyter and execute.

Check Output: Look for 5 CSV files and mean/std prints.

Troubleshoot: If errors (e.g., no data), recall the flow and ask me.

Adjust: Confirm codes match your MF_Schemes sheet.

It’s 10:07 PM IST now, so rest well! You’ll ace this tomorrow. Let me know if you need a
refresher!

one more:#5
import pandas as pd
student_df = pd.read_csv('STUDENT (1).csv')
print(student_df)
student_list = list(student_df['STUDENT_NAME'])
student_tuple = tuple(student_df['AGE'])
student_dict = dict(zip(student_df['STUDENT_NO'],
student_df['STUDENT_NAME']))
print("Subset")
print(student_df.iloc[0:3])
print("--------------------------------------------------------------
-----------")
print(student_df[student_df['AGE'] > 21])
print("--------------------------------------------------------------
-----------")
print(student_df[['STUDENT_NAME', 'ELECTIVE']])
print("--------------------------------------------------------------
-----------")
print("\n")
print("List")
print(student_list[0:2])
print("--------------------------------------------------------------
-----------") 
print(student_list[-3:])
print("--------------------------------------------------------------
-----------")
print(student_list[::2])
print("--------------------------------------------------------------
-----------")
print("\n")
print("Tuple Subsets (Student Ages):")
print(student_tuple[0:2])
print("--------------------------------------------------------------
-----------")
print(student_tuple[-3:])
print("--------------------------------------------------------------
-----------")
print(student_tuple[::2])
print("--------------------------------------------------------------
-----------")
print("\n")
print("Dictionary Subsets (STUDENT_NO: STUDENT_NAME):")
print(student_dict[10002])
print("--------------------------------------------------------------
-----------")
print(list(student_dict.keys()))
print("--------------------------------------------------------------
-----------")
dict_items = list(student_dict.items())
print(dict_items[0:3])

Excellent! Let’s break down the logic of the code for Question 5 in a simple and
memorable way, similar to the previous explanations. This code reads student data
from a CSV file, creates different data structures (list, tuple, dictionary), and
demonstrates subsets from each, aligning with your assignment’s requirement to
"Demonstrate how subsets can be read from DataFrame, List, Tuple, and Dict data
structures." I’ll use analogies and key points to help you remember it tomorrow. The
current time is 10:10 PM IST on October 22, 2025, so we’ll keep this concise for your
review.
Overall Goal 

Imagine you’re a school clerk organizing student records from a "register" (CSV file)
into different "folders" (DataFrame, list, tuple, dictionary) and showing specific
"sections" (subsets) of each folder to the principal. The code does this for the STUDENT
(1).csv file.

Step-by-Step Logic
1. Opening the Register (Import and Read CSV)

Code:

python

import pandas as pd
student_df = pd.read_csv('STUDENT (1).csv')
print(student_df)

Logic:

import pandas as pd : Brings in a tool to read and manage tables, like

getting a ledger book.

pd.read_csv('STUDENT (1).csv') : Opens the student register file and

loads it into student_df , a table with columns like STUDENT_NO ,


STUDENT_NAME , AGE , and ELECTIVE .

print(student_df) : Shows the entire register to check all students.

Memorable Tip: Think of flipping open a class register and glancing at all the
names and details.

2. Creating Different Folders (Data Structures)

Code:

python

student_list = list(student_df['STUDENT_NAME'])
student_tuple = tuple(student_df['AGE'])
student_dict = dict(zip(student_df['STUDENT_NO'], student_df['STUDENT_

 

Logic:
student_list = list(student_df['STUDENT_NAME']) : Pulls the 
STUDENT_NAME column into a flexible "name list," like a roll call sheet you can

edit.

student_tuple = tuple(student_df['AGE']) : Turns the AGE column into a


fixed "age list" (tuple), like a locked age record.

student_dict = dict(zip(student_df['STUDENT_NO'],

student_df['STUDENT_NAME'])) : Pairs STUDENT_NO and STUDENT_NAME into

a "student directory," where each number is a key to a name.

Memorable Tip: Picture sorting student names into a notepad, ages into a
sealed envelope, and a phonebook linking IDs to names.

3. Showing DataFrame Subsets (Table Sections)

Code:

python

print("Subset")
print(student_df.iloc[0:3])
print("---------------------------------------------------------------
print(student_df[student_df['AGE'] > 21])
print("---------------------------------------------------------------
print(student_df[['STUDENT_NAME', 'ELECTIVE']])
print("---------------------------------------------------------------
print("\n")

 

Logic:

student_df.iloc[0:3] : Shows the first 3 rows (students 0 to 2), like


flipping to the top of the register.

student_df[student_df['AGE'] > 21] : Filters for students older than 21,


like picking out seniors.

student_df[['STUDENT_NAME', 'ELECTIVE']] : Selects only the name and

elective columns, like focusing on specific fields.

Memorable Tip: Think of showing the principal the first few entries, the older
students, and just the names and courses.

4. Showing List Subsets (Name List Sections)

Code:
python 

print("List")
print(student_list[0:2])
print("---------------------------------------------------------------
print(student_list[-3:])
print("---------------------------------------------------------------
print(student_list[::2])
print("---------------------------------------------------------------
print("\n")

 

Logic:

student_list[0:2] : Shows the first 2 names, like reading the top of the roll
call.

student_list[-3:] : Shows the last 3 names, like checking the end.

student_list[::2] : Shows every other name, like skipping every second

student.

Memorable Tip: Picture skimming the name list for the start, end, or every
other name.

5. Showing Tuple Subsets (Age List Sections)

Code:

python

print("Tuple Subsets (Student Ages):")


print(student_tuple[0:2])
print("---------------------------------------------------------------
print(student_tuple[-3:])
print("---------------------------------------------------------------
print(student_tuple[::2])
print("---------------------------------------------------------------
print("\n")

 

Logic:

student_tuple[0:2] : Shows the first 2 ages, like peeking at the top of the

locked age record.

student_tuple[-3:] : Shows the last 3 ages, like checking the end.


student_tuple[::2] : Shows every other age, like skipping every second 
number.

Memorable Tip: Think of glancing at the age envelope’s start, end, or every
other age.

6. Showing Dictionary Subsets (Directory Sections)

Code:

python

print("Dictionary Subsets (STUDENT_NO: STUDENT_NAME):")


print(student_dict[10002])
print("---------------------------------------------------------------
print(list(student_dict.keys()))
print("---------------------------------------------------------------
dict_items = list(student_dict.items())
print(dict_items[0:3])

 

Logic:

student_dict[10002] : Looks up the name for student number 10002, like


finding a name in the phonebook

You might also like