🐼 Pandas Series

Unit 5 — The #1 tool for data analysis — load, explore, filter, and manipulate tabular data with ease.

What is a Series?

A Series is a 1D labeled array — like a single column in a spreadsheet with an index.

python
import pandas as pd # Create Series sales = pd.Series([45000,52000,48000,61000], index=["Q1","Q2","Q3","Q4"], name="Sales_2024") print(sales) print("\nDtype:", sales.dtype) print("Index:", sales.index.tolist())
Output
Q1 45000 Q2 52000 Q3 48000 Q4 61000 Name: Sales_2024, dtype: int64 Dtype: int64 Index: ['Q1', 'Q2', 'Q3', 'Q4']

Series Operations

python
s = pd.Series({"Cairo":450000,"Alex":280000,"Giza":195000,"Aswan":90000}) print(s["Cairo"]) # 450000 print(s[s > 200000]) # Filter print(s.sort_values()) # Ascending print(s.sort_values(ascending=False).head(2)) # Top 2 # Stats print(f"Total: {s.sum():,}") print(f"Mean: {s.mean():,.0f}") print(f"Max: {s.max():,} ({s.idxmax()})")
Output
450000 Cairo 450000 Alex 280000 dtype: int64 Aswan 90000 Giza 195000 Alex 280000 Cairo 450000 dtype: int64 Cairo 450000 Alex 280000 dtype: int64 Total: 1,015,000 Mean: 253,750 Max: 450,000 (Cairo)
🎯 TASK Practice: Pandas Series
Create a Series of monthly revenue. Calculate month-over-month growth, find the best/worst months, and normalize the values to 0-100 scale.
Starter code:
python
import pandas as pd revenue = pd.Series( [450000,520000,480000,610000,580000,720000, 650000,590000,710000,780000,820000,950000], index=[f"Month_{i}" for i in range(1,13)] ) # Month-over-month % growth growth = revenue.pct_change() * 100 # Best and worst best_month = revenue.idxmax() worst_month = revenue.idxmin() # Normalize 0-100 normalized = (revenue - revenue.min()) / (revenue.max() - revenue.min()) * 100 print(f"Best: {best_month} ({revenue[best_month]:,})") print(f"Worst: {worst_month} ({revenue[worst_month]:,})") print(f"\nGrowth (first 4):") print(growth.head(4).round(1)) print(f"\nNormalized (first 4):") print(normalized.head(4).round(1))

🐼 DataFrames

Unit 5 — The #1 tool for data analysis — load, explore, filter, and manipulate tabular data with ease.

Creating DataFrames

python
import pandas as pd # From dictionary (most common) data = { "Name": ["Ahmed","Sara","Omar","Layla","Karim"], "Dept": ["Sales","IT","Sales","HR","IT"], "Salary": [9500,12000,8800,10200,15000], "Years": [3,5,2,7,8], } df = pd.DataFrame(data) print(df) print("\nShape:", df.shape) # (5, 4) print("Columns:", df.columns.tolist())
Output
Name Dept Salary Years 0 Ahmed Sales 9500 3 1 Sara IT 12000 5 2 Omar Sales 8800 2 3 Layla HR 10200 7 4 Karim IT 15000 8 Shape: (5, 4) Columns: ['Name', 'Dept', 'Salary', 'Years']

Key Attributes & Operations

python
# Access columns print(df["Salary"]) # Series print(df[["Name","Salary"]]) # DataFrame # Add new column df["Annual"] = df["Salary"] * 12 df["Senior"] = df["Years"] >= 5 # Basic aggregation print(df["Salary"].mean()) # 11100.0 print(df.groupby("Dept")["Salary"].mean()) # Remove column df = df.drop("Annual", axis=1)
💡 Tip: A DataFrame is essentially a dictionary of Series — each column is a Series with the same index.
🎯 TASK Practice: DataFrames
Create a sales DataFrame with 6 records. Add calculated columns: revenue (units × price), profit (revenue × margin%), and grade (A/B/C based on revenue).
Starter code:
python
import pandas as pd data = { "Product": ["Laptop","Phone","Tablet","Monitor","Keyboard","Mouse"], "Units": [5, 20, 12, 8, 30, 50], "Price": [12000, 6500, 4200, 8000, 450, 200], "Margin": [0.25, 0.20, 0.22, 0.18, 0.35, 0.40], } df = pd.DataFrame(data) df["Revenue"] = df["Units"] * df["Price"] df["Profit"] = df["Revenue"] * df["Margin"] df["Grade"] = df["Revenue"].apply( lambda r: "A" if r > 50000 else "B" if r > 20000 else "C" ) print(df[["Product","Revenue","Profit","Grade"]].sort_values("Revenue", ascending=False).to_string(index=False)) print(f"\nTotal Revenue: {df['Revenue'].sum():,}") print(f"Total Profit: {df['Profit'].sum():,}")

🐼 Reading CSV & Excel

Unit 5 — The #1 tool for data analysis — load, explore, filter, and manipulate tabular data with ease.

Reading CSV

python
import pandas as pd # Basic df = pd.read_csv("sales.csv") # With options df = pd.read_csv("sales.csv", encoding = "utf-8", # Handle special characters parse_dates = ["Date"], # Auto-parse date columns index_col = "Order_ID", # Set as index usecols = ["Date","Product","Sales"], # Only load these nrows = 1000, # Load only first 1000 rows skiprows = [1,2], # Skip specific rows na_values = ["N/A","--"], # Treat as NaN dtype = {"Sales": float} # Force column type ) print(df.shape) print(df.head(3))

Reading Excel

python
# Single sheet df = pd.read_excel("report.xlsx") # Specific sheet df = pd.read_excel("report.xlsx", sheet_name="Sales_Q4") # All sheets all_sheets = pd.read_excel("report.xlsx", sheet_name=None) for name, df in all_sheets.items(): print(f"{name}: {df.shape}") # Write df.to_csv("output.csv", index=False) df.to_excel("output.xlsx",index=False, sheet_name="Results") df.to_json("output.json", orient="records")
💡 Tip: Always use encoding="utf-8" for Arabic text. Use index=False when saving to avoid an extra row-number column.
🎯 TASK Practice: Reading CSV & Excel
Create sample data, save to CSV and Excel, then read back with various options: only specific columns, filter while reading, and handle missing values.
Starter code:
python
import pandas as pd import io # Sample data (simulating a CSV file) csv_data = """Date,Product,Region,Sales,Units 2024-01-01,Laptop,Cairo,12000,1 2024-01-02,Phone,Alex,6500,2 2024-01-03,Tablet,Cairo,,3 2024-01-04,Laptop,Giza,24000,2 2024-01-05,Phone,Cairo,6500,1 """ # Read from string (simulating file) df = pd.read_csv( io.StringIO(csv_data), parse_dates=["Date"], usecols=["Date","Product","Sales","Units"], na_values=["", " "] ) print("Raw data:") print(df) print(f"\nMissing values: {df.isnull().sum().sum()}") # Fill missing Sales with product median df["Sales"] = df.groupby("Product")["Sales"].transform( lambda x: x.fillna(x.median()) ) print("\nAfter filling missing:") print(df)

🐼 Exploring Your Data

Unit 5 — The #1 tool for data analysis — load, explore, filter, and manipulate tabular data with ease.

First Look Commands

python
import pandas as pd df = pd.read_csv("sales.csv") print(df.head()) # First 5 rows print(df.tail(3)) # Last 3 rows print(df.sample(5)) # Random 5 rows print(df.shape) # (rows, cols) print(df.columns.tolist()) print(df.dtypes) print(df.index)

info() and describe()

python
# info() — types, missing values, memory df.info() # describe() — statistics for numeric columns print(df.describe()) # describe for all columns (including strings) print(df.describe(include="all")) # Individual column stats print(df["Sales"].value_counts().head()) # Frequency print(df["Region"].unique()) # Unique values print(df["Region"].nunique()) # Count unique print(df["Sales"].quantile([0.25,0.5,0.75]))
Output
<class 'pandas.core.frame.DataFrame'> RangeIndex: 1000 entries Date 1000 non-null datetime64 Region 998 non-null object ← 2 missing! Sales 1000 non-null float64
💡 Tip: Always run df.info() first on any new dataset. It shows data types AND missing value counts at a glance.
🎯 TASK Practice: Exploring Your Data
Build a complete data exploration report: load data, print shape, dtypes, missing values, basic stats, and top/bottom performers.
Starter code:
python
import pandas as pd import numpy as np # Create sample dataset np.random.seed(42) n = 100 df = pd.DataFrame({ "Date": pd.date_range("2024-01", periods=n, freq="D"), "Product": np.random.choice(["Laptop","Phone","Tablet"], n), "Region": np.random.choice(["Cairo","Alex","Giza"], n), "Sales": np.random.normal(50000, 15000, n).round(0), "Units": np.random.randint(1, 20, n), }) # Add some missing values df.loc[np.random.choice(n, 5), "Sales"] = np.nan print("=== DATA EXPLORATION REPORT ===") print(f"Shape: {df.shape}") print(f"Date range: {df.Date.min().date()} to {df.Date.max().date()}") print(f"\nColumn types:") print(df.dtypes) print(f"\nMissing values:") print(df.isnull().sum()) print(f"\nSales statistics:") print(df["Sales"].describe().round(0)) print(f"\nTop 5 sales days:") print(df.nlargest(5, "Sales")[["Date","Product","Region","Sales"]])

🐼 Selecting & Filtering

Unit 5 — The #1 tool for data analysis — load, explore, filter, and manipulate tabular data with ease.

Column & Row Selection

python
import pandas as pd df = pd.read_csv("sales.csv") # Single column → Series sales_col = df["Sales"] # Multiple columns → DataFrame subset = df[["Product","Region","Sales"]] # Rows by boolean condition cairo_sales = df[df["Region"] == "Cairo"] high_sales = df[df["Sales"] > 50000] # Multiple conditions cairo_high = df[(df["Region"] == "Cairo") & (df["Sales"] > 30000)] # isin — match multiple values north = df[df["Region"].isin(["Cairo","Alex","Port Said"])] # String matching laptops = df[df["Product"].str.contains("Laptop", case=False)]

loc and iloc

python
# loc — label-based (use column NAMES) df.loc[0] # Row with index 0 df.loc[0, "Product"] # Specific cell df.loc[0:5, ["Product","Sales"]] # Range + columns # iloc — position-based (use NUMBERS) df.iloc[0] # First row df.iloc[0, 2] # Row 0, column 2 df.iloc[:5, :3] # First 5 rows, first 3 cols df.iloc[[0,2,4], :] # Specific rows # query() — SQL-like syntax result = df.query("Sales > 50000 and Region == 'Cairo'") print(result.head())
💡 Tip: Use query() for complex filters — it's more readable: df.query('Sales > 5000 & Region == "Cairo"')
🎯 TASK Practice: Selecting & Filtering
Filter and analyze a sales dataset: find top 10 sales, Cairo-only data, products costing between 5000-15000, and use query() for a complex filter.
Starter code:
python
import pandas as pd, numpy as np np.random.seed(42) df = pd.DataFrame({ "Product": np.random.choice(["Laptop","Phone","Tablet","Monitor"],100), "Region": np.random.choice(["Cairo","Alex","Giza","Aswan"],100), "Sales": np.random.randint(5000, 80000, 100), "Units": np.random.randint(1, 10, 100), }) # 1. Top 10 by sales top10 = df.nlargest(10, "Sales")[["Product","Region","Sales"]] print("Top 10 sales:") print(top10.head(3)) # 2. Cairo only cairo = df[df["Region"] == ???] print(f"\nCairo rows: {len(cairo)}") # 3. Sales between 20000-60000 mid = df[(df["Sales"] >= 20000) & (df["Sales"] <= 60000)] print(f"Mid-range: {len(mid)} rows") # 4. query() result = df.query("Sales > 50000 and Region in ['Cairo','Alex']") print(f"\nHigh Cairo/Alex: {len(result)} rows") print(result.groupby("Region")["Sales"].mean().round(0))

🐼 Adding & Modifying Columns

Unit 5 — The #1 tool for data analysis — load, explore, filter, and manipulate tabular data with ease.

Adding New Columns

python
import pandas as pd df = pd.DataFrame({ "Product": ["Laptop","Phone","Tablet"], "Price": [12000, 6500, 4200], "Units": [5, 20, 12], }) # Simple calculation df["Revenue"] = df["Price"] * df["Units"] df["VAT"] = df["Revenue"] * 0.14 df["Total"] = df["Revenue"] + df["VAT"] # Conditional column df["Tier"] = df["Revenue"].apply( lambda x: "Premium" if x > 50000 else "Standard" ) # String operation df["Label"] = df["Product"].str.upper() + "_2024" print(df)
Output
Product Price Units Revenue VAT Total Tier Label 0 Laptop 12000 5 60000 8400.0 68400.0 Premium LAPTOP_2024 1 Phone 6500 20 130000 18200.0 148200.0 Premium PHONE_2024 2 Tablet 4200 12 50400 7056.0 57456.0 Premium TABLET_2024

assign() and insert()

python
# assign — chainable, returns new DataFrame df2 = (df .assign(Profit = lambda x: x["Revenue"] * 0.20) .assign(Profitable= lambda x: x["Profit"] > 10000) ) # insert — add column at specific position df.insert(2, "Category", "Electronics") print(df.columns.tolist())
💡 Tip: Prefer assign() for data transformation pipelines — it doesn't modify the original and supports method chaining.
🎯 TASK Practice: Adding & Modifying Columns
Build a complete salary analysis: add columns for annual salary, tax bracket, net salary, performance bonus (based on years), and seniority level.
Starter code:
python
import pandas as pd employees = pd.DataFrame({ "Name": ["Ahmed","Sara","Omar","Layla","Karim","Dina"], "Salary": [9500, 12000, 8800, 15000, 7500, 18000], "Years": [3, 5, 2, 8, 1, 10], "Dept": ["Sales","IT","Sales","IT","HR","IT"], }) # Annual salary employees["Annual"] = employees["Salary"] * 12 # Tax: 25% if annual > 120000, else 15% employees["Tax_Rate"] = employees["Annual"].apply( lambda x: 0.25 if x > 120000 else 0.15 ) employees["Tax"] = employees["Annual"] * employees["Tax_Rate"] employees["Net"] = employees["Annual"] - employees["Tax"] # Performance bonus: 3 months salary if years > 5, else 1 month employees["Bonus"] = employees.apply( lambda r: r["Salary"] * (3 if r["Years"] > 5 else 1), axis=1 ) # Seniority employees["Level"] = pd.cut(employees["Years"], bins=[0,2,5,10,100], labels=["Junior","Mid","Senior","Expert"] ) print(employees[["Name","Annual","Tax","Net","Bonus","Level"]].to_string(index=False))

🐼 Sorting & Ranking

Unit 5 — The #1 tool for data analysis — load, explore, filter, and manipulate tabular data with ease.

Sorting DataFrames

python
import pandas as pd df = pd.DataFrame({ "Name": ["Ahmed","Sara","Omar","Layla","Karim"], "Dept": ["Sales","IT","Sales","HR","IT"], "Salary": [9500,12000,8800,10200,15000], "Years": [3,5,2,7,8], }) # Sort by one column by_salary = df.sort_values("Salary", ascending=False) print(by_salary[["Name","Salary"]].to_string(index=False)) # Sort by multiple columns by_dept_salary = df.sort_values(["Dept","Salary"], ascending=[True,False]) print(by_dept_salary[["Name","Dept","Salary"]].to_string(index=False))
Output
Name Salary Karim 15000 Sara 12000 Layla 10200 Ahmed 9500 Omar 8800 Name Dept Salary Layla HR 10200 Sara IT 15000 Karim IT 12000 Ahmed Sales 9500 Omar Sales 8800

Ranking

python
# rank() — assign ranks df["Salary_Rank"] = df["Salary"].rank(ascending=False).astype(int) df["Years_Rank"] = df["Years"].rank(ascending=False,method="dense").astype(int) # nlargest / nsmallest top3 = df.nlargest(3, "Salary")[["Name","Salary","Salary_Rank"]] print(top3.to_string(index=False)) # Percentile rank df["Pct_Rank"] = df["Salary"].rank(pct=True).round(2) print(df[["Name","Salary","Pct_Rank"]].to_string(index=False))
🎯 TASK Practice: Sorting & Ranking
Rank products by 3 criteria: revenue, units sold, and profit margin. Create a weighted composite score and final ranking.
Starter code:
python
import pandas as pd products = pd.DataFrame({ "Product": ["Laptop","Phone","Tablet","Monitor","Keyboard"], "Revenue": [60000,130000,50400,64000,13500], "Units": [5, 20, 12, 8, 30], "Margin": [0.25,0.20,0.22,0.18,0.35], }) # Rank each metric (1=best) products["Rev_Rank"] = products["Revenue"].rank(ascending=False) products["Units_Rank"] = products["Units"].rank(ascending=False) products["Margin_Rank"] = products["Margin"].rank(ascending=False) # Weighted composite (revenue 50%, units 30%, margin 20%) products["Score"] = ( products["Rev_Rank"] * 0.50 + products["Units_Rank"] * 0.30 + products["Margin_Rank"] * 0.20 ) # Final ranking (lower score = better) products["Final_Rank"] = products["Score"].rank().astype(int) result = products.sort_values("Final_Rank")[["Product","Revenue","Units","Margin","Final_Rank"]] print(result.to_string(index=False))

🐼 apply() & map()

Unit 5 — The #1 tool for data analysis — load, explore, filter, and manipulate tabular data with ease.

apply() — Apply Function to Axis

python
import pandas as pd df = pd.DataFrame({ "Q1": [45000,38000,28000], "Q2": [52000,42000,31000], "Q3": [48000,45000,29000], "Q4": [61000,55000,38000], }, index=["Cairo","Alex","Giza"]) # Apply to each column (axis=0) print("Column totals:") print(df.apply(sum, axis=0)) # Apply to each row (axis=1) print("\nRow totals:") print(df.apply(sum, axis=1)) # Custom function def growth_rate(row): return (row.iloc[-1] - row.iloc[0]) / row.iloc[0] * 100 print("\nAnnual growth rate:") print(df.apply(growth_rate, axis=1).round(1))
Output
Column totals: Q1 111000 Q2 125000 Q3 122000 Q4 154000 dtype: int64 Row totals: Cairo 206000 Alex 180000 Giza 126000 dtype: int64 Annual growth rate: Cairo 35.6 Alex 44.7 Giza 35.7 dtype: float64

map() and applymap()

python
# map() — transform a Series df2 = pd.DataFrame({"Name":["Ahmed","Sara","Omar"],"Dept":["Sales","IT","Sales"]}) # map with dict — replace values dept_map = {"Sales": "Commercial", "IT": "Technology", "HR": "People"} df2["Dept_Full"] = df2["Dept"].map(dept_map) # map with function df2["Name_Upper"] = df2["Name"].map(str.upper) print(df2)
💡 Tip: Use apply() for complex logic, map() for simple value substitution. Both are faster than Python loops.
🎯 TASK Practice: apply() & map()
Use apply() to create an employee performance score based on salary, years, and department bonus. Use map() to translate department codes to full names.
Starter code:
python
import pandas as pd df = pd.DataFrame({ "Name": ["Ahmed","Sara","Omar","Layla","Karim"], "Dept": ["S","IT","S","HR","IT"], "Salary": [9500,12000,8800,10200,15000], "Years": [3,5,2,7,8], "Target": [100000,120000,90000,105000,150000], "Sales": [95000,125000,85000,108000,160000], }) # Map dept codes to full names dept_names = {"S":"Sales","IT":"Information Technology","HR":"Human Resources"} df["Department"] = df["Dept"].map(dept_names) # Performance score using apply on each row def calc_score(row): target_pct = row["Sales"] / row["Target"] exp_bonus = min(row["Years"] / 10, 0.2) return round((target_pct + exp_bonus) * 50, 1) df["Score"] = df.apply(calc_score, axis=1) df["Grade"] = df["Score"].map(lambda s: "A" if s>=55 else "B" if s>=48 else "C") print(df[["Name","Department","Score","Grade"]].to_string(index=False))

🐼 String Methods in Pandas

Unit 5 — The #1 tool for data analysis — load, explore, filter, and manipulate tabular data with ease.

The .str Accessor

python
import pandas as pd df = pd.DataFrame({ "Name": [" ahmed hassan ", "SARA ALI", "omar ibrahim"], "Email": ["ahmed@corp.com", "sara@tech.io", "omar@biz.net"], "Phone": ["010-1234-5678", "011-9876-5432", "012-4567-8901"], "City": ["cairo", "ALEX", "giza "], }) # Cleaning df["Name"] = df["Name"].str.strip().str.title() df["City"] = df["City"].str.strip().str.title() df["Email"] = df["Email"].str.lower() df["Phone"] = df["Phone"].str.replace("-","") print(df)
Output
Name Email Phone City 0 Ahmed Hassan ahmed@corp.com 01012345678 Cairo 1 Sara Ali sara@tech.io 01198765432 Alex 2 Omar Ibrahim omar@biz.net 01245678901 Giza

Extract, Split, and Search

python
# Extract domain from email df["Domain"] = df["Email"].str.split("@").str[1] # Check if email contains certain domain df["Is_Corp"] = df["Email"].str.contains("corp|biz", regex=True) # Extract phone operator (first 3 digits) df["Operator"] = df["Phone"].str[:3] # Count characters df["Name_Length"] = df["Name"].str.len() # Find position df["At_Position"] = df["Email"].str.find("@") print(df[["Name","Domain","Is_Corp","Operator"]])
🎯 TASK Practice: String Methods in Pandas
Clean a messy customer dataset: standardize names, validate emails, extract domain, clean phone numbers, and flag invalid records.
Starter code:
python
import pandas as pd customers = pd.DataFrame({ "raw_name": [" AHMED HASSAN ","sara ali","Omar Ibrahim"," LAYLA "], "email": ["ahmed@company.com","SARA@TECH.IO","not-an-email","layla@corp.net"], "phone": ["010-1234-5678","011 9876 5432","012.4567.8901","ABC-DEF-GHIJ"], "city": ["CAIRO","alex ","GIZA"," CAIRO "], }) # Clean name customers["name"] = customers["raw_name"].str.strip().str.title() # Clean email customers["email"] = customers["email"].str.lower().str.strip() # Validate email (simple check) customers["email_valid"] = customers["email"].str.contains( r"^[\w.]+@[\w.]+\.[a-z]{2,}$", regex=True ) # Extract domain customers["domain"] = customers["email"].str.split("@").str[-1] # Clean phone (digits only) customers["phone_clean"] = customers["phone"].str.replace(r"[^0-9]","",regex=True) customers["phone_valid"] = customers["phone_clean"].str.len() == 11 # Clean city customers["city"] = customers["city"].str.strip().str.title() print(customers[["name","email_valid","domain","phone_valid","city"]].to_string(index=False))

🐼 Working with Dates

Unit 5 — The #1 tool for data analysis — load, explore, filter, and manipulate tabular data with ease.

Creating Date Columns

python
import pandas as pd df = pd.DataFrame({ "Order_Date": ["2024-01-15","2024-02-28","2024-03-10","2024-04-01"], "Amount": [5000, 8500, 3200, 12000], }) # Convert string to datetime df["Order_Date"] = pd.to_datetime(df["Order_Date"]) # Extract date parts df["Year"] = df["Order_Date"].dt.year df["Month"] = df["Order_Date"].dt.month df["Day"] = df["Order_Date"].dt.day df["Quarter"] = df["Order_Date"].dt.quarter df["Weekday"] = df["Order_Date"].dt.day_name() df["Week"] = df["Order_Date"].dt.isocalendar().week print(df[["Order_Date","Month","Quarter","Weekday"]])
Output
Order_Date Month Quarter Weekday 0 2024-01-15 1 1 Monday 1 2024-02-28 2 1 Wednesday 2 2024-03-10 3 1 Sunday 3 2024-04-01 4 2 Monday

Date Operations

python
# Date arithmetic today = pd.Timestamp("today").normalize() df["Age_Days"] = (today - df["Order_Date"]).dt.days # Date ranges dates = pd.date_range("2024-01-01", periods=12, freq="ME") print(dates) # Group by month df["Month_Period"] = df["Order_Date"].dt.to_period("M") monthly = df.groupby("Month_Period")["Amount"].sum() print(monthly)
💡 Tip: Always convert date columns with pd.to_datetime() right after loading data — it enables all date operations.
🎯 TASK Practice: Working with Dates
Analyze a year of daily sales data: group by month, quarter, and weekday. Find the best/worst performing periods.
Starter code:
python
import pandas as pd, numpy as np np.random.seed(42) # Generate a year of daily sales dates = pd.date_range("2024-01-01","2024-12-31",freq="D") df = pd.DataFrame({ "Date": dates, "Sales": np.random.normal(50000,12000,len(dates)).round(0), }) df["Month"] = df["Date"].dt.month_name() df["Quarter"] = "Q" + df["Date"].dt.quarter.astype(str) df["Weekday"] = df["Date"].dt.day_name() # Monthly analysis monthly = df.groupby("Month")["Sales"].agg(["sum","mean"]).round(0) best_month = df.groupby("Month")["Sales"].sum().idxmax() # Weekday analysis by_day = df.groupby("Weekday")["Sales"].mean().sort_values(ascending=False) print("Best month:", best_month) print("\nTop 3 weekdays:") print(by_day.head(3).round(0)) print("\nQuarterly totals:") print(df.groupby("Quarter")["Sales"].sum().round(0))