Cursor rule for pandas code with method chains, vectorised ops, explicit date parsing, nullable dtypes, observed groupby and pandas 3 Copy-on-Write habits.
.cursor/rules/python-data-science-with-pandas.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for pandas code with method chains, vectorised ops, explicit date parsing, nullable dtypes, observed groupby and pandas 3 Copy-on-Write habits."
globs: "**/*"
alwaysApply: false
---
# Python Data Analysis with pandas
Applies to: notebooks and Python modules that load, clean, aggregate and summarise tabular data with pandas and NumPy.
Version baseline: checked against the pandas 3.x documentation. pandas 3.0 (January 2026) made Copy-on-Write always on and a dedicated string dtype the default. Read the pinned pandas version in `pyproject.toml` or `requirements*.txt`. Code here also runs on pandas 2.2+, but do not rely on pre-3.0 chained assignment or object-dtype strings.
## Imports
```python
import numpy as np
import pandas as pd
```
Import plotting libraries (matplotlib, seaborn, plotly) only in the modules that plot. Use built-in generics (`list[str]`, `dict[str, float]`) in type hints, not `typing.List`.
## DataFrame habits
- Prefer method chains that return new frames (`assign`, `query`, `pipe`, `rename`, `sort_values`). Inside a chain, reference the current frame with a lambda (`lambda d: ...`), not an outer variable that may be stale.
- Use vectorised column operations instead of Python loops: `df["total"] = df["price"] * df["quantity"]`. Use `np.where`/`np.select` for conditional columns. Reach for `.apply(axis=1)` only when no vectorised form exists.
- Index explicitly. Use `.loc[row_labels, cols]` for labels and `.iloc[positions]` for positions. Never mix `range(len(df))` with `.loc`: on a non-default index, that creates new rows.
- Copy-on-Write rules (pandas 3): assign through one `.loc` call (`df.loc[mask, "col"] = value`). Chained assignment such as `df["col"][mask] = value` no longer modifies `df`. Never use `inplace=True` to save memory; it does not reliably avoid copies.
- Functions take a DataFrame and return a new one. Do not mutate arguments; call `df = df.copy()` first if you must assign columns.
## Cleaning
Make every cleaning decision explicit and reviewable:
```python
def clean_orders(df: pd.DataFrame) -> pd.DataFrame:
"""Return a cleaned copy of raw order rows."""
return (
df
.drop_duplicates(subset=["order_id"])
.assign(
order_date=lambda d: pd.to_datetime(d["order_date"], format="%Y-%m-%d", errors="coerce"),
amount=lambda d: pd.to_numeric(d["amount"], errors="coerce"),
region=lambda d: d["region"].fillna("Unknown").astype("category"),
customer_id=lambda d: d["customer_id"].astype("Int64"), # nullable integer
)
.dropna(subset=["order_date", "amount"])
.reset_index(drop=True)
)
```
- Parse dates with an explicit `format` (or `dayfirst=True` when the data is day-first). Ambiguous strings like `05/01/2026` are otherwise read month-first without an error.
- Use nullable dtypes (`"Int64"`, `"boolean"`, `"string"`) when missing values are possible. `astype("int64")` raises on missing values.
- Compute imputation statistics inside the chain (`lambda d: d["x"].fillna(d["x"].median())`). Document why imputing is acceptable for the analysis.
- Do not silently drop outliers. Flag them (for example with an IQR rule) and let the analysis decide. Report how many rows each step removed.
```python
def flag_iqr_outliers(df: pd.DataFrame, column: str, k: float = 1.5) -> pd.DataFrame:
q1, q3 = df[column].quantile([0.25, 0.75])
iqr = q3 - q1
return df.assign(**{f"{column}_outlier": ~df[column].between(q1 - k * iqr, q3 + k * iqr)})
```
## Aggregation and reshaping
```python
summary = (
df.groupby(["region", "year"], observed=True)
.agg(
total_sales=("amount", "sum"),
avg_order=("amount", "mean"),
orders=("order_id", "count"),
unique_customers=("customer_id", "nunique"),
)
.reset_index()
)
pivot = pd.pivot_table(
df, values="amount", index="region", columns="quarter",
aggfunc="sum", fill_value=0, margins=True, observed=True,
)
```
- Pass `observed=True` when grouping by categoricals so empty category combinations are not created.
- `count` excludes missing values and `size` includes them. Pick the one the question needs.
## Memory
Downcast only after measuring with `df.memory_usage(deep=True)`, and return a new frame:
```python
def optimize_dtypes(df: pd.DataFrame, max_unique_ratio: float = 0.5) -> pd.DataFrame:
out = df.copy()
for col in out.select_dtypes(include="integer").columns:
out[col] = pd.to_numeric(out[col], downcast="integer")
for col in out.select_dtypes(include="float").columns:
out[col] = pd.to_numeric(out[col], downcast="float")
for col in out.select_dtypes(include=["object", "string"]).columns:
if out[col].nunique() / max(len(out), 1) < max_unique_ratio:
out[col] = out[col].astype("category")
return out
```
Float downcasting loses precision. Do not downcast money or other values that are compared for equality.
## Verify before finishing
- Assert row counts and key uniqueness after each cleaning step (for example `assert df["order_id"].is_unique`).
- Add a small synthetic DataFrame test for each transformation, including missing values, duplicate keys and a non-default index.
- Run the project's tests and linters, and re-run the notebook from a clean kernel so the results do not depend on hidden state.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
data
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
An analyst asks Cursor to write or refactor a pandas cleaning and reporting step for raw CSV exports.
orders.csv has order_id, order_date (YYYY-MM-DD, some invalid), amount (string, sometimes 'n/a'), region (may be blank), customer_id (may be blank). Write clean_orders(df) and a monthly sales summary per region. We run pandas 3.1.
Illustrative; not a recorded model run. A clean_orders function that returns a new frame. It drops duplicates on order_id, parses order_date with format='%Y-%m-%d' and errors='coerce', converts amount with to_numeric(errors='coerce'), fills region with 'Unknown' as a category and stores customer_id as nullable Int64, then drops rows with an invalid date or amount. The summary uses groupby(..., observed=True).agg(named aggregations). There are no row loops and no chained assignment. Row counts are reported after each step, and the tests use a small synthetic frame.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/python-data-science-with-pandas.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Python Data Science with Pandas: Cleaning, Aggregation and Copy-on-Write Rules project conventions"
globs: "**/*"
alwaysApply: false
---
# Python Data Analysis with pandas
Applies to: notebooks and Python modules that load, clean, aggregate and summarise tabular data with pandas and NumPy.
Version baseline: checked against the pandas 3.x documentation. pandas 3.0 (January 2026) made Copy-on-Write always on and a dedicated string dtype the default. Read the pinned pandas version in `pyproject.toml` or `requirements*.txt`. Code here also runs on pandas 2.2+, but do not rely on pre-3.0 chained assignment or object-dtype strings.
## Imports
```python
import numpy as np
import pandas as pd
```
Import plotting libraries (matplotlib, seaborn, plotly) only in the modules that plot. Use built-in generics (`list[str]`, `dict[str, float]`) in type hints, not `typing.List`.
## DataFrame habits
- Prefer method chains that return new frames (`assign`, `query`, `pipe`, `rename`, `sort_values`). Inside a chain, reference the current frame with a lambda (`lambda d: ...`), not an outer variable that may be stale.
- Use vectorised column operations instead of Python loops: `df["total"] = df["price"] * df["quantity"]`. Use `np.where`/`np.select` for conditional columns. Reach for `.apply(axis=1)` only when no vectorised form exists.
- Index explicitly. Use `.loc[row_labels, cols]` for labels and `.iloc[positions]` for positions. Never mix `range(len(df))` with `.loc`: on a non-default index, that creates new rows.
- Copy-on-Write rules (pandas 3): assign through one `.loc` call (`df.loc[mask, "col"] = value`). Chained assignment such as `df["col"][mask] = value` no longer modifies `df`. Never use `inplace=True` to save memory; it does not reliably avoid copies.
- Functions take a DataFrame and return a new one. Do not mutate arguments; call `df = df.copy()` first if you must assign columns.
## Cleaning
Make every cleaning decision explicit and reviewable:
```python
def clean_orders(df: pd.DataFrame) -> pd.DataFrame:
"""Return a cleaned copy of raw order rows."""
return (
df
.drop_duplicates(subset=["order_id"])
.assign(
order_date=lambda d: pd.to_datetime(d["order_date"], format="%Y-%m-%d", errors="coerce"),
amount=lambda d: pd.to_numeric(d["amount"], errors="coerce"),
region=lambda d: d["region"].fillna("Unknown").astype("category"),
customer_id=lambda d: d["customer_id"].astype("Int64"), # nullable integer
)
.dropna(subset=["order_date", "amount"])
.reset_index(drop=True)
)
```
- Parse dates with an explicit `format` (or `dayfirst=True` when the data is day-first). Ambiguous strings like `05/01/2026` are otherwise read month-first without an error.
- Use nullable dtypes (`"Int64"`, `"boolean"`, `"string"`) when missing values are possible. `astype("int64")` raises on missing values.
- Compute imputation statistics inside the chain (`lambda d: d["x"].fillna(d["x"].median())`). Document why imputing is acceptable for the analysis.
- Do not silently drop outliers. Flag them (for example with an IQR rule) and let the analysis decide. Report how many rows each step removed.
```python
def flag_iqr_outliers(df: pd.DataFrame, column: str, k: float = 1.5) -> pd.DataFrame:
q1, q3 = df[column].quantile([0.25, 0.75])
iqr = q3 - q1
return df.assign(**{f"{column}_outlier": ~df[column].between(q1 - k * iqr, q3 + k * iqr)})
```
## Aggregation and reshaping
```python
summary = (
df.groupby(["region", "year"], observed=True)
.agg(
total_sales=("amount", "sum"),
avg_order=("amount", "mean"),
orders=("order_id", "count"),
unique_customers=("customer_id", "nunique"),
)
.reset_index()
)
pivot = pd.pivot_table(
df, values="amount", index="region", columns="quarter",
aggfunc="sum", fill_value=0, margins=True, observed=True,
)
```
- Pass `observed=True` when grouping by categoricals so empty category combinations are not created.
- `count` excludes missing values and `size` includes them. Pick the one the question needs.
## Memory
Downcast only after measuring with `df.memory_usage(deep=True)`, and return a new frame:
```python
def optimize_dtypes(df: pd.DataFrame, max_unique_ratio: float = 0.5) -> pd.DataFrame:
out = df.copy()
for col in out.select_dtypes(include="integer").columns:
out[col] = pd.to_numeric(out[col], downcast="integer")
for col in out.select_dtypes(include="float").columns:
out[col] = pd.to_numeric(out[col], downcast="float")
for col in out.select_dtypes(include=["object", "string"]).columns:
if out[col].nunique() / max(len(out), 1) < max_unique_ratio:
out[col] = out[col].astype("category")
return out
```
Float downcasting loses precision. Do not downcast money or other values that are compared for equality.
## Verify before finishing
- Assert row counts and key uniqueness after each cleaning step (for example `assert df["order_id"].is_unique`).
- Add a small synthetic DataFrame test for each transformation, including missing values, duplicate keys and a non-default index.
- Run the project's tests and linters, and re-run the notebook from a clean kernel so the results do not depend on hidden state.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.