# ============================================================
# PYTHON DATA STRUCTURES - ALL OPERATIONS REFERENCE GUIDE
# ============================================================
import array
import numpy as np
import pandas as pd
# ==============================================================
# 1. LISTS
# ==============================================================
print("\n" + "="*60)
print(" LISTS")
print("="*60)
lst = [10, 20, 30, 40, 50]
# --- Creation ---
empty_list = []
from_range = list(range(1, 6)) # [1, 2, 3, 4, 5]
nested_list = [[1, 2], [3, 4], [5, 6]]
mixed_list = [1, "hello", 3.14, True]
# --- Accessing ---
print("\n--- Accessing ---")
print("Index 0 :", lst[0]) # 10
print("Index -1 :", lst[-1]) # 50
print("Slice [1:3] :", lst[1:3]) # [20, 30]
print("Slice [::2] :", lst[::2]) # [10, 30, 50]
print("Reverse [::-1]:", lst[::-1]) # [50, 40, 30, 20, 10]
# --- Modifying ---
print("\n--- Modifying ---")
lst[0] = 100
print("After lst[0]=100 :", lst)
[Link](60)
print("After append(60) :", lst)
[Link](1, 15)
print("After insert(1,15):", lst)
[Link]([70, 80])
print("After extend :", lst)
[Link](15)
print("After remove(15) :", lst)
popped = [Link]()
print("After pop() :", lst, "| Popped:", popped)
popped_idx = [Link](1)
print("After pop(1) :", lst, "| Popped:", popped_idx)
del lst[0]
print("After del lst[0] :", lst)
[Link]()
print("After clear() :", lst)
# Re-initialize
lst = [10, 20, 30, 40, 50, 30]
# --- Searching ---
print("\n--- Searching ---")
print("Index of 30 :", [Link](30)) # First occurrence
print("Count of 30 :", [Link](30))
print("30 in lst :", 30 in lst)
print("99 not in lst :", 99 not in lst)
# --- Sorting & Ordering ---
print("\n--- Sorting & Ordering ---")
lst2 = [3, 1, 4, 1, 5, 9, 2, 6]
[Link]()
print("After sort() :", lst2)
[Link](reverse=True)
print("After sort(desc) :", lst2)
print("sorted() (new list) :", sorted(lst2))
[Link]()
print("After reverse() :", lst2)
# --- Copying ---
print("\n--- Copying ---")
original = [1, 2, 3]
shallow = [Link]()
also_copy = list(original)
import copy
deep_copy = [Link]([[1, 2], [3, 4]])
# --- Aggregation ---
print("\n--- Aggregation ---")
nums = [3, 1, 4, 1, 5, 9, 2, 6]
print("len :", len(nums))
print("sum :", sum(nums))
print("min :", min(nums))
print("max :", max(nums))
# --- List Comprehensions ---
print("\n--- List Comprehensions ---")
squares = [x**2 for x in range(1, 6)]
even_sq = [x**2 for x in range(1, 11) if x % 2 == 0]
flat = [n for sub in [[1,2],[3,4]] for n in sub]
print("Squares :", squares)
print("Even squares:", even_sq)
print("Flattened :", flat)
# --- Other Utilities ---
print("\n--- Other Utilities ---")
a = [1, 2, 3]
b = [4, 5, 6]
print("Concatenation (+) :", a + b)
print("Repetition (*2) :", a * 2)
print("zip two lists :", list(zip(a, b)))
print("enumerate :", list(enumerate(a)))
print("map (x*2) :", list(map(lambda x: x*2, a)))
print("filter (x>1) :", list(filter(lambda x: x > 1, a)))
# ==============================================================
# 2. DICTIONARIES
# ==============================================================
print("\n" + "="*60)
print(" DICTIONARIES")
print("="*60)
d = {"name": "Alice", "age": 25, "city": "Hyderabad"}
# --- Creation ---
empty_dict = {}
from_keys = [Link](["a", "b", "c"], 0)
dict_comp = {x: x**2 for x in range(1, 6)}
# --- Accessing ---
print("\n--- Accessing ---")
print("d['name'] :", d["name"])
print("[Link]('age') :", [Link]("age"))
print("[Link]('x', 'N/A') :", [Link]("x", "N/A"))
print("keys() :", list([Link]()))
print("values() :", list([Link]()))
print("items() :", list([Link]()))
# --- Modifying ---
print("\n--- Modifying ---")
d["email"] = "alice@[Link]"
print("After add key :", d)
d["age"] = 26
print("After update age :", d)
[Link]({"city": "Mumbai", "phone": "9999999999"})
print("After update() :", d)
removed = [Link]("phone")
print("After pop('phone') :", d, "| Removed:", removed)
[Link]("country", "India")
print("After setdefault :", d)
popped_item = [Link]()
print("After popitem() :", d, "| Removed:", popped_item)
[Link]()
print("After clear() :", d)
# Re-initialize
d = {"name": "Alice", "age": 26, "city": "Mumbai"}
# --- Searching ---
print("\n--- Searching ---")
print("'name' in d :", "name" in d)
print("'x' not in d :", "x" not in d)
print("'Alice' in [Link]():", "Alice" in [Link]())
# --- Merging ---
print("\n--- Merging ---")
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
merged = {**d1, **d2} # d2 overwrites d1
print("Merged {**d1,**d2} :", merged)
d1 |= d2 # Python 3.9+
print("After d1 |= d2 :", d1)
# --- Copying ---
shallow_d = [Link]()
import copy
deep_d = [Link](d)
# --- Iteration ---
print("\n--- Iteration ---")
for key, val in [Link]():
print(f" {key}: {val}")
# --- Dict Comprehension ---
print("\n--- Dict Comprehension ---")
squared = {k: v**2 for k, v in {"a": 2, "b": 3}.items()}
print("Squared values :", squared)
# --- Other ---
print("\n--- Other ---")
print("len(d) :", len(d))
# ==============================================================
# 3. TUPLES
# ==============================================================
print("\n" + "="*60)
print(" TUPLES")
print("="*60)
t = (10, 20, 30, 40, 50, 30)
# --- Creation ---
empty_tuple = ()
single_element = (42,) # Trailing comma required
from_list = tuple([1, 2, 3])
nested_tuple = ((1, 2), (3, 4))
# --- Accessing ---
print("\n--- Accessing ---")
print("t[0] :", t[0])
print("t[-1] :", t[-1])
print("t[1:4] :", t[1:4])
print("t[::2] :", t[::2])
print("t[::-1] :", t[::-1])
# --- Searching ---
print("\n--- Searching ---")
print("index(30) :", [Link](30)) # First occurrence
print("count(30) :", [Link](30))
print("30 in t :", 30 in t)
# --- Aggregation ---
print("\n--- Aggregation ---")
print("len(t) :", len(t))
print("sum(t) :", sum(t))
print("min(t) :", min(t))
print("max(t) :", max(t))
# --- Operations ---
print("\n--- Operations ---")
a_t = (1, 2, 3)
b_t = (4, 5, 6)
print("Concat (+) :", a_t + b_t)
print("Repeat (*2) :", a_t * 2)
print("sorted() :", sorted(t)) # Returns a list
print("list(t) :", list(t)) # Convert to list
# --- Unpacking ---
print("\n--- Unpacking ---")
x, y, z = (1, 2, 3)
print("x,y,z = :", x, y, z)
first, *rest = (10, 20, 30, 40)
print("first, *rest :", first, rest)
*start, last = (10, 20, 30, 40)
print("*start, last :", start, last)
# --- Named Tuple ---
print("\n--- Named Tuple ---")
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print("Named tuple :", p)
print("p.x, p.y :", p.x, p.y)
# --- Tuple as Dictionary Key ---
coord_map = {(0, 0): "origin", (1, 0): "right"}
print("Tuple as key :", coord_map[(0, 0)])
# ==============================================================
# 4. STRINGS
# ==============================================================
print("\n" + "="*60)
print(" STRINGS")
print("="*60)
s = "Hello, World! Hello Python"
# --- Creation ---
s1 = 'single quotes'
s2 = "double quotes"
s3 = """multi
line"""
s4 = r"raw \n string"
s5 = f"Formatted: {2 + 3}"
# --- Accessing ---
print("\n--- Accessing ---")
print("s[0] :", s[0])
print("s[-1] :", s[-1])
print("s[0:5] :", s[0:5])
print("s[::2] :", s[::2])
print("s[::-1] :", s[::-1])
# --- Case Operations ---
print("\n--- Case Operations ---")
print("upper() :", [Link]())
print("lower() :", [Link]())
print("title() :", [Link]())
print("capitalize() :", [Link]())
print("swapcase() :", [Link]())
print("casefold() :", [Link]())
# --- Searching ---
print("\n--- Searching ---")
print("find('Hello') :", [Link]("Hello"))
print("rfind('Hello') :", [Link]("Hello"))
print("index('World') :", [Link]("World"))
print("count('Hello') :", [Link]("Hello"))
print("startswith('H'):", [Link]("H"))
print("endswith('on') :", [Link]("on"))
print("'Hello' in s :", "Hello" in s)
# --- Modifying (returns new string) ---
print("\n--- Modifying ---")
print("replace() :", [Link]("Hello", "Hi"))
print("strip() :", " hi ".strip())
print("lstrip() :", " hi ".lstrip())
print("rstrip() :", " hi ".rstrip())
print("removeprefix() :", "Hello World".removeprefix("Hello "))
print("removesuffix() :", "Hello World".removesuffix(" World"))
# --- Splitting & Joining ---
print("\n--- Splitting & Joining ---")
words = [Link](" ")
print("split(' ') :", words)
print("rsplit(' ', 1) :", [Link](" ", 1))
print("splitlines() :", "a\nb\nc".splitlines())
print("join :", "-".join(["a", "b", "c"]))
# --- Formatting ---
print("\n--- Formatting ---")
print("format() :", "Hi, {}! You are {} yrs".format("Alice", 25))
print("f-string :", f"Pi is approx {3.14159:.2f}")
print("% formatting :", "Name: %s, Age: %d" % ("Bob", 30))
print("center(30,'*') :", "Hello".center(30, "*"))
print("ljust(20,'.') :", "Hello".ljust(20, "."))
print("rjust(20,'.') :", "Hello".rjust(20, "."))
print("zfill(10) :", "42".zfill(10))
# --- Checking ---
print("\n--- Checking ---")
print("isalpha() :", "Hello".isalpha())
print("isdigit() :", "1234".isdigit())
print("isalnum() :", "Hello123".isalnum())
print("isspace() :", " ".isspace())
print("isupper() :", "HELLO".isupper())
print("islower() :", "hello".islower())
print("istitle() :", "Hello World".istitle())
print("isnumeric() :", "123".isnumeric())
print("isdecimal() :", "123".isdecimal())
# --- Encoding ---
print("\n--- Encoding ---")
encoded = "hello".encode("utf-8")
print("encode utf-8 :", encoded)
print("decode utf-8 :", [Link]("utf-8"))
# --- Other ---
print("\n--- Other ---")
print("len() :", len(s))
print("ord('A') :", ord("A"))
print("chr(65) :", chr(65))
print("'ab' * 3 :", "ab" * 3)
print("'ab' + 'cd' :", "ab" + "cd")
# ==============================================================
# 5. ARRAY (built-in array module)
# ==============================================================
print("\n" + "="*60)
print(" ARRAY (array module)")
print("="*60)
arr = [Link]("i", [10, 20, 30, 40, 50]) # 'i' = signed int
# --- Creation ---
arr_float = [Link]("f", [1.1, 2.2, 3.3])
# Typecodes: 'b' signed char, 'B' unsigned char, 'i' int,
# 'I' unsigned int, 'f' float, 'd' double, etc.
# --- Accessing ---
print("\n--- Accessing ---")
print("arr[0] :", arr[0])
print("arr[-1] :", arr[-1])
print("arr[1:3] :", arr[1:3].tolist())
# --- Modifying ---
print("\n--- Modifying ---")
[Link](60)
print("After append(60) :", [Link]())
[Link](1, 15)
print("After insert(1,15) :", [Link]())
[Link]([70, 80])
print("After extend([70,80]) :", [Link]())
[Link](15)
print("After remove(15) :", [Link]())
popped = [Link]()
print("After pop() :", [Link](), "| Popped:", popped)
# --- Searching ---
print("\n--- Searching ---")
print("index(30) :", [Link](30))
print("count(30) :", [Link](30))
# --- Utilities ---
print("\n--- Utilities ---")
print("len(arr) :", len(arr))
print("buffer_info :", arr.buffer_info()) # (address, length)
print("typecode :", [Link])
[Link]()
print("After reverse:", [Link]())
print("tolist() :", [Link]())
print("tobytes() :", [Link]())
arr2 = [Link]("i")
[Link]([Link]())
print("frombytes :", [Link]())
# ==============================================================
# 6. NUMPY
# ==============================================================
print("\n" + "="*60)
print(" NUMPY")
print("="*60)
# --- Creation ---
print("\n--- Creation ---")
a1 = [Link]([1, 2, 3, 4, 5])
a2 = [Link]([[1, 2, 3], [4, 5, 6]])
z = [Link]((2, 3))
o = [Link]((2, 3))
e = [Link](3)
r = [Link](0, 10, 2)
l = [Link](0, 1, 5)
rand_arr = [Link](3, 3)
rand_int = [Link](0, 10, (2, 3))
full_arr = [Link]((2, 2), 7)
diag_arr = [Link]([1, 2, 3])
print("zeros :\n", z)
print("arange :", r)
print("linspace :", l)
# --- Attributes ---
print("\n--- Attributes ---")
print("shape :", [Link])
print("size :", [Link])
print("ndim :", [Link])
print("dtype :", [Link])
print("itemsize :", [Link], "bytes")
print("nbytes :", [Link], "bytes")
# --- Indexing & Slicing ---
print("\n--- Indexing & Slicing ---")
print("a1[0] :", a1[0])
print("a2[1][2] :", a2[1][2])
print("a2[0, :] :", a2[0, :])
print("a2[:, 1] :", a2[:, 1])
print("a1[1:4] :", a1[1:4])
print("a1[a1 > 2] :", a1[a1 > 2]) # Boolean indexing
print("a1[[0,2,4]] :", a1[[0, 2, 4]]) # Fancy indexing
# --- Reshaping ---
print("\n--- Reshaping ---")
print("reshape(1,6) :", [Link](1, 6))
print("flatten() :", [Link]())
print("ravel() :", [Link]())
print("T (transpose) :\n", a2.T)
print("expand_dims :", np.expand_dims(a1, axis=0).shape)
print("squeeze :", [Link]([Link]([[[1, 2, 3]]])).shape)
# --- Math Operations ---
print("\n--- Math Operations ---")
x = [Link]([1, 2, 3, 4])
y = [Link]([5, 6, 7, 8])
print("x + y :", x + y)
print("x - y :", x - y)
print("x * y :", x * y)
print("x / y :", x / y)
print("x ** 2 :", x ** 2)
print("x // y :", x // y)
print("x % 3 :", x % 3)
print("[Link] :", [Link](x, y))
print("[Link] :", [Link](x, y))
print("[Link] :", [Link](x, y))
print("[Link] :", [Link](x, y))
print("[Link] :", [Link](x, 2))
# --- Universal Functions (ufuncs) ---
print("\n--- Universal Functions ---")
print("sqrt :", [Link](x))
print("exp :", [Link](x))
print("log :", [Link](x))
print("log2 :", np.log2(x))
print("log10 :", np.log10(x))
print("sin :", [Link](x))
print("cos :", [Link](x))
print("tan :", [Link](x))
print("abs :", [Link]([-1, -2, 3]))
print("ceil :", [Link]([1.2, 2.7]))
print("floor :", [Link]([1.2, 2.7]))
print("round :", [Link]([1.235, 2.765], 2))
# --- Aggregation ---
print("\n--- Aggregation ---")
m = [Link]([[1, 2, 3], [4, 5, 6]])
print("sum() :", [Link]())
print("sum(axis=0) :", [Link](axis=0))
print("sum(axis=1) :", [Link](axis=1))
print("mean() :", [Link]())
print("median() :", [Link](m))
print("std() :", [Link]())
print("var() :", [Link]())
print("min() :", [Link]())
print("max() :", [Link]())
print("argmin() :", [Link]())
print("argmax() :", [Link]())
print("cumsum() :", [Link]())
print("cumprod() :", [Link]())
print("prod() :", [Link]())
# --- Linear Algebra ---
print("\n--- Linear Algebra ---")
A = [Link]([[1, 2], [3, 4]])
B = [Link]([[5, 6], [7, 8]])
print("dot product :\n", [Link](A, B))
print("matmul (@) :\n", A @ B)
print("det :", [Link](A))
print("inv :\n", [Link](A))
eigenvalues, eigenvectors = [Link](A)
print("eigenvalues :", eigenvalues)
print("norm :", [Link](A))
U, S, Vt = [Link](A)
print("SVD S values :", S)
print("trace :", [Link](A))
print("rank :", [Link].matrix_rank(A))
# --- Sorting & Searching ---
print("\n--- Sorting & Searching ---")
unsorted = [Link]([3, 1, 4, 1, 5, 9, 2, 6])
print("sort() :", [Link](unsorted))
print("argsort() :", [Link](unsorted))
print("where(>3) :", [Link](unsorted > 3))
print("nonzero :", [Link](unsorted))
# --- Set Operations ---
print("\n--- Set Operations ---")
p = [Link]([1, 2, 3, 4, 5])
q = [Link]([3, 4, 5, 6, 7])
print("unique :", [Link]([1, 1, 2, 2, 3]))
print("union1d :", np.union1d(p, q))
print("intersect1d :", np.intersect1d(p, q))
print("setdiff1d :", np.setdiff1d(p, q))
print("in1d :", np.in1d(p, q))
# --- Concatenation & Stacking ---
print("\n--- Concatenation & Stacking ---")
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
print("concatenate :", [Link]([a, b]))
print("vstack :\n", [Link]([a, b]))
print("hstack :", [Link]([a, b]))
print("stack axis=0 :\n", [Link]([a, b], axis=0))
print("split :", [Link](a, 3))
# --- Type Conversion ---
print("\n--- Type Conversion ---")
print("astype float :", [Link](float))
print("astype str :", [Link](str))
# --- Copy & View ---
view_arr = [Link]() # Shares data
copy_arr = [Link]() # Independent copy
print("shares memory(view):", np.shares_memory(a1, view_arr))
print("shares memory(copy):", np.shares_memory(a1, copy_arr))
# --- Boolean & Comparison ---
print("\n--- Boolean & Comparison ---")
print("any(>4) :", [Link](a1 > 4))
print("all(>0) :", [Link](a1 > 0))
print("isnan :", [Link]([Link]([1.0, [Link]])))
print("isinf :", [Link]([Link]([1.0, [Link]])))
# ==============================================================
# 7. PANDAS
# ==============================================================
print("\n" + "="*60)
print(" PANDAS")
print("="*60)
# ---- Series ----
print("\n--- Series ---")
s_pd = [Link]([10, 20, 30, 40, 50], index=["a","b","c","d","e"])
print(s_pd)
print("s['a'] :", s_pd["a"])
print("s[1:3] :", s_pd[1:3].tolist())
print("s > 25 :\n", s_pd[s_pd > 25])
print("[Link] :", s_pd.dtype)
print("[Link] :", s_pd.values)
print("[Link] :", s_pd.[Link]())
# ---- DataFrame Creation ----
print("\n--- DataFrame Creation ---")
data = {
"Name" : ["Alice", "Bob", "Charlie", "David", "Eva"],
"Age" : [25, 30, 35, 28, 22],
"City" : ["Hyderabad","Mumbai","Delhi","Pune","Chennai"],
"Score" : [88.5, 92.0, 78.3, 95.1, 83.7],
"Pass" : [True, True, False, True, True]
}
df = [Link](data)
print(df)
# Also from list of dicts, numpy array, CSV, etc.
df_from_list = [Link]([{"a":1,"b":2},{"a":3,"b":4}])
df_numpy = [Link]([Link](3,3), columns=["X","Y","Z"])
# ---- Inspection ----
print("\n--- Inspection ---")
print("head(2) :\n", [Link](2))
print("tail(2) :\n", [Link](2))
print("shape :", [Link])
print("ndim :", [Link])
print("size :", [Link])
print("columns :", [Link]())
print("index :", [Link]())
print("dtypes :\n", [Link])
print("info :"); [Link]()
print("describe() :\n", [Link]())
print("value_counts :\n", df["City"].value_counts())
print("nunique :\n", [Link]())
# ---- Accessing ----
print("\n--- Accessing ---")
print("df['Name'] :\n", df["Name"].tolist())
print("df[['Name','Age']]:\n", df[["Name","Age"]])
print("iloc[0] :\n", [Link][0])
print("iloc[0,1] :", [Link][0, 1])
print("iloc[1:3] :\n", [Link][1:3])
print("loc[0] :\n", [Link][0])
print("loc[0,'Name']:", [Link][0, "Name"])
print("at[0,'City'] :", [Link][0, "City"])
print("iat[1,2] :", [Link][1, 2])
# ---- Filtering ----
print("\n--- Filtering ---")
print("Age > 25 :\n", df[df["Age"] > 25])
print("Multiple cond:\n", df[(df["Age"] > 24) & (df["Pass"] == True)])
print("isin() :\n", df[df["City"].isin(["Mumbai","Delhi"])])
print("query() :\n", [Link]("Age > 25 and Score > 80"))
print("between() :\n", df[df["Age"].between(25, 30)])
# ---- Adding / Modifying ----
print("\n--- Adding / Modifying ---")
df["Grade"] = df["Score"].apply(lambda x: "A" if x >= 90 else "B" if x >= 80 else "C")
print("After add 'Grade':\n", df)
df["Score"] = df["Score"].round(0).astype(int)
print("After modify Score:\n", df[["Name","Score"]])
[Link](columns={"Score": "Marks"}, inplace=True)
print("After rename:\n", [Link]())
[Link](columns={"Marks": "Score"}, inplace=True)
# ---- Dropping ----
print("\n--- Dropping ---")
df_drop = [Link](columns=["Grade"])
print("drop column Grade:\n", df_drop.[Link]())
df_drop_row = [Link](index=[0, 1])
print("drop rows 0,1:\n", df_drop_row)
# ---- Sorting ----
print("\n--- Sorting ---")
print("sort_values('Age'):\n", df.sort_values("Age"))
print("sort_values(desc) :\n", df.sort_values("Score", ascending=False))
print("sort_index() :\n", df.sort_index(ascending=False))
# ---- Missing Data ----
print("\n--- Missing Data ---")
df_na = [Link]({"A":[1, [Link], 3], "B":[[Link], 5, 6], "C":[7, 8, [Link]]})
print("isnull():\n", df_na.isnull())
print("isna() :\n", df_na.isna())
print("notnull():\n", df_na.notnull())
print("any NaN :", df_na.isnull().any().any())
print("dropna() :\n", df_na.dropna())
print("fillna(0):\n", df_na.fillna(0))
print("fillna ffill:\n", df_na.ffill())
print("fillna bfill:\n", df_na.bfill())
# ---- Aggregation ----
print("\n--- Aggregation ---")
print("sum() :\n", df["Score"].sum())
print("mean() :", df["Score"].mean())
print("median() :", df["Score"].median())
print("std() :", df["Score"].std())
print("var() :", df["Score"].var())
print("min() :", df["Score"].min())
print("max() :", df["Score"].max())
print("count() :", df["Score"].count())
print("agg() :\n", df["Score"].agg(["min","max","mean","std"]))
# ---- GroupBy ----
print("\n--- GroupBy ---")
print("groupby City sum:\n", [Link]("City")["Score"].sum())
print("groupby Pass mean:\n", [Link]("Pass")["Score"].mean())
print("groupby agg:\n",
[Link]("Pass").agg({"Score": ["mean","max"], "Age": "min"}))
# ---- Merge / Join ----
print("\n--- Merge / Join ---")
df1 = [Link]({"id":[1,2,3], "name":["A","B","C"]})
df2 = [Link]({"id":[2,3,4], "score":[90,85,78]})
print("inner merge:\n", [Link](df1, df2, on="id", how="inner"))
print("left merge :\n", [Link](df1, df2, on="id", how="left"))
print("outer merge:\n", [Link](df1, df2, on="id", how="outer"))
print("concat rows:\n", [Link]([df1, df2], axis=0, ignore_index=True))
print("join :\n", df1.set_index("id").join(df2.set_index("id"), how="left"))
# ---- Pivot Table ----
print("\n--- Pivot Table ---")
df_piv = [Link]({
"Name" : ["Alice","Alice","Bob","Bob"],
"Sub" : ["Math","Sci","Math","Sci"],
"Score": [80, 90, 70, 85]
})
pivot = df_piv.pivot_table(values="Score", index="Name", columns="Sub", aggfunc="mean")
print(pivot)
# ---- Apply / Map ----
print("\n--- Apply / Map ---")
df["UpperName"] = df["Name"].apply([Link])
df["AgeGroup"] = df["Age"].map(lambda x: "Young" if x < 30 else "Senior")
print(df[["Name","UpperName","Age","AgeGroup"]])
# ---- String Operations (str accessor) ----
print("\n--- String Operations ---")
print("[Link]() :\n", df["Name"].[Link]().tolist())
print("[Link]() :\n", df["Name"].[Link]().tolist())
print("[Link] :\n", df["Name"].[Link]("a", case=False).tolist())
print("[Link]:\n", df["Name"].[Link]("A").tolist())
print("[Link]() :\n", df["Name"].[Link]().tolist())
print("[Link] :\n", df["City"].[Link]("Mumbai","Bombay").tolist())
print("[Link] :\n", df["City"].[Link]("m").tolist())
print("[Link] :\n", df["Name"].[Link]().tolist())
# ---- DateTime Operations ----
print("\n--- DateTime Operations ---")
df_dt = [Link]({"date": pd.date_range("2024-01-01", periods=5, freq="D"),
"val": [1, 2, 3, 4, 5]})
print(df_dt)
print("year :", df_dt["date"].[Link]())
print("month :", df_dt["date"].[Link]())
print("day :", df_dt["date"].[Link]())
print("day_name() :", df_dt["date"].dt.day_name().tolist())
print("weekday :", df_dt["date"].[Link]())
# ---- Type Conversion ----
print("\n--- Type Conversion ---")
print("astype str :\n", df["Age"].astype(str).tolist())
print("astype float :\n", df["Score"].astype(float).tolist())
print("to_numeric :", pd.to_numeric(["1","2","3"]))
print("to_datetime :", pd.to_datetime(["2024-01-01","2024-06-15"]).tolist())
# ---- Copying ----
df_copy = [Link]()
# ---- Reset / Set Index ----
print("\n--- Index Operations ---")
df_ri = df.reset_index(drop=True)
df_si = df.set_index("Name")
print("set_index Name:\n", df_si.head(2))
# ---- Duplicates ----
print("\n--- Duplicates ---")
df_dup = [Link]({"A":[1,1,2,3,3],"B":["x","x","y","z","z"]})
print("duplicated() :\n", df_dup.duplicated().tolist())
print("drop_duplicates :\n", df_dup.drop_duplicates())
# ---- Correlation & Covariance ----
print("\n--- Correlation & Covariance ---")
print("corr() :\n", df[["Age","Score"]].corr())
print("cov() :\n", df[["Age","Score"]].cov())
# ---- IO (commented – would need actual files) ----
# df.to_csv("[Link]", index=False)
# df.to_excel("[Link]", index=False)
# df.to_json("[Link]")
# pd.read_csv("[Link]")
# pd.read_excel("[Link]")
# pd.read_json("[Link]")
# pd.read_sql("SELECT * FROM table", connection)
print("\n" + "="*60)
print(" ALL DATA STRUCTURE OPERATIONS COMPLETE!")
print("="*60)