3

I have a time series in a Pandas DataFrame for which I want to add a new column with the (future) minimum values. Specifically, imagine I have the following values in my time series:

 VAL
 1 
 0 
 4 
 3 
 2 
 3 
 4 

I would like to find the minimum values "looking forward". For example, the minimum for the first 2 values is 0, then for the next three values is 2 (0 is no longer considered because, even if it's the overall minimum, it's already in the past), then 3 and finally 4.

 VAL   MIN
 1     0
 0     0
 4     2
 3     2
 2     2
 3     3
 4     4

Any ideas how I can do this efficiently with Pandas or Numpy? Thanks!

rafaelc
  • 57,686
  • 15
  • 58
  • 82
rv123
  • 476
  • 1
  • 3
  • 14

3 Answers3

6

Flip it, use np.minimum.accumulate, flip it back -

In [252]: df['MIN'] = np.minimum.accumulate(df['VAL'][::-1])[::-1]

In [253]: df
Out[253]: 
   VAL  MIN
0    1    0
1    0    0
2    4    2
3    3    2
4    2    2
5    3    3
6    4    4
Divakar
  • 218,885
  • 19
  • 262
  • 358
5

Using cummin

df['MIN'] = df.VAL[::-1].cummin()[::-1]

    VAL  MIN
0    1    0
1    0    0
2    4    2
3    3    2
4    2    2
5    3    3
6    4    4
rafaelc
  • 57,686
  • 15
  • 58
  • 82
3

We can using expanding with min

df['New']=df.VAL.iloc[::-1].expanding(min_periods=1).min()
BENY
  • 317,841
  • 20
  • 164
  • 234