Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rolling min of a Pandas Series without window / cumulative minimum / expanding min

I'm looking for a way to calculate with Python Pandas rolling(*) min of a Series without window.

Let's consider the following Series

In [26]: s = pd.Series([10, 12, 14, 9, 10, 8, 16, 20])
Out[26]:
0    10
1    12
2    14
3     9
4    10
5     8
6    16
7    20
dtype: int64

I would like to get a Series like

0    10
1    10
2    10
3     9
4     9
5     8
6     8
7     8
dtype: int64

I tried

s.rolling().min()

but I'm getting the following error

TypeError: rolling() missing 1 required positional argument: 'window'

I did this

r = s.copy()
val_min = r.iloc[0]
for i, (idx, val) in enumerate(r.iteritems()):
    if i > 0:
        if val < val_min:
            val_min = val
        else:
            r[idx] = val_min

and have a correct answer

In [30]: r
Out[30]:
0    10
1    10
2    10
3     9
4     9
5     8
6     8
7     8
dtype: int64

but I think a Pandas method should probably exist (and be much more efficient) or if it doesn't exist, it should probably be implemented.

(*) "rolling" may not be the appropriate term, maybe it should be named instead a "local" min.

Edit: it's in fact named a cumulative minimum or expanding min

like image 535
scls Avatar asked Dec 07 '22 12:12

scls


1 Answers

Use Series.cummin:

print(s.cummin())
0    10
1    10
2    10
3     9
4     9
5     8
6     8
7     8
dtype: int64
like image 141
jezrael Avatar answered Dec 28 '22 05:12

jezrael