You are viewing v1 of 1. Go to the current version · All versions
Pandas code from a plain-English data task
Describe the transformation or analysis you need and get clean, commented pandas code that handles messy data and explains each step.
Change note: Initial version
Prompt
Write Python pandas code for the following task.
Task: {{task}}
My DataFrame (name, columns with types, and a few sample rows):
{{dataframe}}
Output I want: {{output}}
Guidelines:
- Start with two or three lines on your approach and any assumptions about the data. If an assumption could change the result, say how, and ask me at the end.
- Write idiomatic, readable code using method chaining where it stays clear. No loops over rows unless unavoidable. No deprecated functions.
- Handle the real-world issues likely in this data: missing values, wrong dtypes, duplicate rows, inconsistent text casing, and time zones. Do not silently drop rows; if rows are removed, print how many.
- Add short comments explaining why, not what.
- Include a tiny runnable example with 4-6 made-up rows so I can check the logic before I run it on the full data.
- End with "How to check it": 2-3 assertions or quick checks (row counts, totals, null counts) I can add.
Format: Approach, Code (one block), Example output, How to check it, Questions.Variables
{{task}}TasklongDefault: For each customer, calculate total spend, number of orders, and days since last order. Then flag customers with no order in 90 days as 'at risk'.
{{dataframe}}DataFrame descriptionlongDefault: df_orders: order_id (int), customer_id (int), order_date (string like '2024-03-15'), amount (float, some NaN)
Name, columns, types and a few sample rows.
{{output}}Desired outputtextDefault: A DataFrame with one row per customer, sorted by total spend descending
Example output
**Approach**: Parse dates, aggregate per customer, compute recency from the latest order date in the data (not today's date) so results are reproducible. Missing amounts are treated as 0 spend but still count as orders; tell me if that is wrong.
```python
import pandas as pd
df = df_orders.copy()
df["order_date"] = pd.to_datetime(df["order_date"], errors="coerce")
bad = df["order_date"].isna().sum()
print(f"Unparseable dates dropped: {bad}")
df = df.dropna(subset=["order_date"]).drop_duplicates("order_id")
as_of = df["order_date"].max()
customers = (
df.groupby("customer_id")
.agg(total_spend=("amount", "sum"),
orders=("order_id", "count"),
last_order=("order_date", "max"))
.assign(days_since_last=lambda d: (as_of - d["last_order"]).dt.days)
.assign(at_risk=lambda d: d["days_since_last"] > 90)
.sort_values("total_spend", ascending=False)
.reset_index()
)
```
**Example output**: customer 7: spend 240.0, orders 3, days_since_last 12, at_risk False.
**How to check it**
- assert customers["orders"].sum() == len(df)
- assert abs(customers["total_spend"].sum() - df["amount"].sum()) < 1e-6
**Questions**: Should recency be measured against today instead of the last date in the data?Notes
Asking for a tiny runnable example and assertions makes the output verifiable rather than just plausible. Pasting 3-5 real rows greatly reduces dtype and format mistakes.