HomeCourseModule 08 › Twelve =PY() recipes you'll use

Twelve =PY() recipes you'll use

Module 08 · Python inside Excel — =PY()9 min readIntermediate

What you'll learn

  • Bookmark this lesson
  • Adapt each recipe to your own data
  • Spot which pandas method does what

1 — Sum a column with a condition

=PY(
df = xl("DataTable[#All]", headers=True)
df.loc[df["Region"]=="North", "Revenue"].sum()
)

2 — Count distinct values

=PY(
xl("A2:A1000").nunique()
)

3 — Group-by total

=PY(
df = xl("A1:D1000", headers=True)
df.groupby("Region")["Revenue"].sum().sort_values(ascending=False)
)

4 — Pivot table

=PY(
df = xl("A1:D1000", headers=True)
df.pivot_table(index="Region", columns="Quarter",
               values="Revenue", aggfunc="sum", fill_value=0)
)

5 — Top N by metric

=PY(
df = xl("A1:E1000", headers=True)
df.nlargest(10, "Revenue")
)

6 — Running total

=PY(
df = xl("A1:B100", headers=True).sort_values("Date")
df["RunningTotal"] = df["Amount"].cumsum()
df
)

7 — Percentage of total

=PY(
s = xl("B2:B11")
(s / s.sum() * 100).round(1)
)

8 — Date difference in days

=PY(
df = xl("A1:C100", headers=True)
df["DaysOpen"] = (pd.to_datetime(df["Closed"])
                  - pd.to_datetime(df["Opened"])).dt.days
df
)

9 — Quartile bucketing

=PY(
df = xl("A1:B500", headers=True)
df["Bucket"] = pd.qcut(df["Score"], 4, labels=["Q1","Q2","Q3","Q4"])
df
)

10 — Inner join two ranges

=PY(
orders = xl("OrdersTable[#All]", headers=True)
customers = xl("CustomersTable[#All]", headers=True)
orders.merge(customers, on="CustomerID")
)

11 — Quick linear regression

=PY(
import numpy as np
df = xl("A1:B100", headers=True)
slope, intercept = np.polyfit(df["X"], df["Y"], 1)
{"slope": slope, "intercept": intercept}
)

12 — Heatmap chart

=PY(
import seaborn as sns
df = xl("A1:D1000", headers=True)
pivot = df.pivot_table(index="DayOfWeek", columns="Hour",
                       values="Orders", aggfunc="sum")
sns.heatmap(pivot, cmap="YlGnBu")
)

Key takeaways

  • Most analysis in =PY() is two or three lines.
  • Bookmark this lesson — you'll come back to it.
  • If you keep wanting a recipe that isn't here, that's a great cue to ask in contact.

Adapt one

Pick recipe #3, #5, or #10. Build a small dataset on a new sheet and make it run in your own workbook.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.