'Dataframe column: to find local maxima

In the below dataframe the column "CumRetperTrade" is a column which consists of a few vertical vectors (=sequences of numbers) separated by zeros. (= these vectors correspond to non-zero elements of column "Portfolio"). I would like to find the local maxima of every non-zero vector contained in column "CumRetperTrade"
To be precise, I would like to transform (using vectorization - or other - methods) column "CumRetperTrade" to the column "PeakCumRet" (desired result) which provides maxima for every vector contained in column "CumRetperTrade" its local max value. The numeric example is below. Thanks in advance.

import numpy as np
import pandas as pd
df1 = pd.DataFrame({"Portfolio": [1, 1, 1, 0 , 0, 0, 1, 1, 1],
"CumRetperTrade": [3, 2, 1, 0 , 0, 0, 4, 2, 1],
"PeakCumRet": [3, 3, 3, 0 , 0, 0, 4, 4, 4]})
df1

Portfolio   CumRetperTrade  PeakCumRet
1           3               3
1           2               3
1           1               3
0           0               0
0           0               0
0           0               0
1           4               4
1           2               4
1           1               4


Solution 1:[1]

You can use :

df1['PeakCumRet'] = (df1.groupby(df1['Portfolio'].ne(df1['Portfolio'].shift()).cumsum())
                     ['CumRetperTrade'].transform('max')
                     )

Output:

   Portfolio  CumRetperTrade  PeakCumRet
0          1               3           3
1          1               2           3
2          1               1           3
3          0               0           0
4          0               0           0
5          0               0           0
6          1               4           4
7          1               2           4
8          1               1           4

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway