How do I attach a group’s value to every row with transform?

Put each day’s mean return on every stock’s row with groupby transform, attach each stock’s cumulative return to the right rows, and see why apply with group_keys=True does not fit back into the panel.

After this lesson, you can put a group’s result, such as the day’s mean return, on every row of a panel.

How do I put the day’s mean on every row?

.groupby("date")["stock_return"].transform("mean") computes each date’s mean and repeats it on every row of that date, so the result has one value per row, 24, while .mean() gives one per date, 8. On 2 March, the mean of the three returns is 0.29%, and AAA’s return of 1.20% is 0.91 percentage points above it.

\[ \bar r_t = \frac{1}{3}\sum_{j} r_{j,t}, \qquad e_{j,t} = r_{j,t} - \bar r_t \]

Here \(r_{j,t}\) is stock \(j\)’s return on day \(t\), \(\bar r_t\) the day’s mean, which is the return of a portfolio with a third in each stock, and \(e_{j,t}\) the stock’s excess return.

The panel holds three made-up stocks’ daily returns in decimals on eight weekdays, one row per stock and date. np.repeat repeats each date three times and np.tile repeats the three tickers eight times, as in the lesson on joining arrays, and .ravel() reads the return matrix row by row in the same order. Assigning the eight date-labelled means directly leaves all 24 rows missing, because pandas matches the dates with the row numbers 0 to 23.

The following box puts the day’s mean on every row and computes the excess returns.

import numpy as np
import pandas as pd

returns = np.column_stack([
    [0.0120, -0.0085, 0.0034, -0.0151, 0.0062, 0.0097, -0.0023, 0.0045],
    [-0.0064, 0.0102, -0.0130, 0.0058, -0.0011, 0.0076, 0.0149, -0.0092],
    [0.0031, -0.0047, 0.0088, 0.0015, -0.0203, 0.0124, 0.0006, 0.0071],
])
dates = pd.bdate_range("2026-03-02", periods=8)
panel = pd.DataFrame({
    "date": np.repeat(dates, 3),
    "ticker": np.tile(["AAA", "BBB", "CCC"], 8),
    "stock_return": returns.ravel(),
})
by_date = panel.groupby("date")["stock_return"]
panel["portfolio_return"] = by_date.transform("mean")
panel["excess_return"] = panel["stock_return"] - panel["portfolio_return"]
print(by_date.mean().shape, panel["portfolio_return"].shape)
print(panel.head(3).round(5))
print(panel.assign(direct=by_date.mean())["direct"].isna().sum())
(8,) (24,)
        date ticker  stock_return  portfolio_return  excess_return
0 2026-03-02    AAA        0.0120            0.0029         0.0091
1 2026-03-02    BBB       -0.0064            0.0029        -0.0093
2 2026-03-02    CCC        0.0031            0.0029         0.0002
24

How do I attach each stock’s cumulative return?

A function passed to .transform() gets each stock’s returns and returns one value per row, so cumulative_return, which compounds the returns, attaches each stock’s cumulative return to its own rows. AAA’s cumulative return is 0.3398% after two days and 0.96% through 11 March.

\[ C_{j,t} = \prod_{s \le t} (1 + r_{j,s}) - 1 \]

.apply(cumulative_return) gives the same numbers, but its default group_keys=True adds the ticker to the row labels, so assigning the result to the panel raises a TypeError. group_keys=False keeps the panel’s row numbers.

The following box attaches the cumulative returns and tries the default apply.

def cumulative_return(stock_return):
    return (1 + stock_return).cumprod() - 1

by_stock = panel.groupby("ticker")["stock_return"]
panel["cumulative_return"] = by_stock.transform(cumulative_return)
print(panel.loc[panel["ticker"] == "AAA", ["date", "stock_return", "cumulative_return"]].round(6).to_string())
try:
    panel["with_keys"] = by_stock.apply(cumulative_return)
except TypeError as error:
    print(type(error).__name__)
print(panel.groupby("ticker", group_keys=False)["stock_return"].apply(cumulative_return).equals(panel["cumulative_return"]))
         date  stock_return  cumulative_return
0  2026-03-02        0.0120           0.012000
3  2026-03-03       -0.0085           0.003398
6  2026-03-04        0.0034           0.006810
9  2026-03-05       -0.0151          -0.008393
12 2026-03-06        0.0062          -0.002245
15 2026-03-09        0.0097           0.007433
18 2026-03-10       -0.0023           0.005116
21 2026-03-11        0.0045           0.009639
TypeError
True

Your turn

For 2 March, print each stock’s excess return divided by the day’s sample standard deviation, rounded to three decimals. You should see 0.989 for AAA, −1.011 for BBB and 0.022 for CCC.

transform("std") puts each day’s standard deviation on the day’s three rows.

panel["z_score"] = panel["excess_return"] / by_date.transform("std")
print(panel.loc[panel["date"] == "2026-03-02", ["ticker", "z_score"]].round(3).to_string(index=False))
ticker  z_score
   AAA    0.989
   BBB   -1.011
   CCC    0.022