| 1 | import pandas as pd # old client interface |
| 2 | import pandasCore as pd # new client interface |
| 3 | |
| 4 | # 12 e-commerce orders |
| 5 | orders = { |
| 6 | "order_id": [101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112], |
| 7 | "customer": ["alice", "bob", "carla", "alice", "deepak", "bob", |
| 8 | "erin", "carla", "deepak", "farid", "erin", "alice"], |
| 9 | "region": ["North", "South", "North", "West", "South", "West", |
| 10 | "North", "South", "West", "North", "South", "West"], |
| 11 | "category": ["Electronics", "Books", "Electronics", "Home", "Books", "Home", |
| 12 | "Electronics", "Books", "Home", "Electronics", "Books", "Home"], |
| 13 | "units": [3, 10, 1, 5, 7, 2, 4, 9, 6, 1, 8, 3], |
| 14 | "unit_price": [199.0, 12.5, 999.0, 49.0, 15.0, 80.0, |
| 15 | 250.0, 11.0, 60.0, 1200.0, 14.5, 55.0], |
| 16 | "rating": [5, 4, 5, 3, 4, 2, 5, 4, 3, 5, 4, 3], |
| 17 | } |
| 18 | df = pd.DataFrame(orders) |
| 19 | |
| 20 | # derived column |
| 21 | df = df.assign(revenue=df["units"] * df["unit_price"]) |
| 22 | |
| 23 | # boolean filter |
| 24 | big = df[df["revenue"] >= 300].reset_index(drop=True) |
| 25 | |
| 26 | # groupby + agg |
| 27 | by_region = df.groupby("region").agg({"revenue": "sum", "units": "mean"}).sort_index() |
| 28 | |
| 29 | # named aggregation |
| 30 | by_cat = df.groupby("category").agg( |
| 31 | total_rev=("revenue", "sum"), avg_rating=("rating", "mean")).sort_index() |
| 32 | |
| 33 | # where / mask |
| 34 | hi = df["rating"].where(df["rating"] >= 4) |
| 35 | lo = df["rating"].mask(df["rating"] >= 4) |
| 36 | |
| 37 | # pivot table |
| 38 | pivot = df.pivot_table(values="revenue", index="region", columns="category", |
| 39 | aggfunc="sum", fill_value=0.0).sort_index() |
| 40 | |
| 41 | # left merge |
| 42 | meta = {"region": ["North", "South", "West"], |
| 43 | "manager": ["Nadia", "Sven", "Wendy"]} |
| 44 | merged = df.merge(pd.DataFrame(meta), on="region", how="left") |
| 45 | |
| 46 | # top 3 by revenue |
| 47 | top = df.nlargest(3, "revenue").reset_index(drop=True) |
| 48 | |
| 49 | # string accessor |
| 50 | names = df["customer"].str.upper() |
| 51 | |
| 52 | # cut into tiers |
| 53 | tiers = pd.cut(df["revenue"], bins=[0, 100, 500, 100000], |
| 54 | labels=["small", "medium", "large"]) |
| 55 | |
| 56 | # value counts |
| 57 | counts = df["region"].value_counts().sort_index() |
| 58 | |
| 59 | # drop duplicates |
| 60 | unique = df.drop_duplicates(subset="customer").reset_index(drop=True) |