1

Have a df of readings as follows:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(1000, size=100), index=range(100), columns = ['reading'])

Want to find the greatest rise and the greatest fall for each row based on its index, which theoretically may be achieved using the formula...

enter image description here

How can this be coded?

Tried:

df.assign(gr8Rise=df.rolling(df.index).apply(lambda x: x[-1]-x[0], raw=True).max())

...and failed with ValueError: window must be an integer

UPDATE: Based on @jezrael dataset the output for gr8Rise is expected as follows:

enter image description here

reservoirinvest
  • 1,463
  • 2
  • 16
  • 32

1 Answers1

1

Use:

np.random.seed(2019)

df = pd.DataFrame(np.random.randint(100, size=10), index=range(10), columns = ['reading'])

df['gr8Rise'] = [df['reading'].rolling(x).apply(lambda x: x[0]-x[-1], raw=True).max() 
                 for x in range(1, len(df)+1)]
df.loc[0, 'gr8Rise']= np.nan
print (df)
   reading  gr8Rise
0       72      NaN
1       31     41.0
2       37     64.0
3       88     59.0
4       62     73.0
5       24     76.0
6       29     72.0
7       15     57.0
8       12     60.0
9       16     56.0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252