0

I have 2 columns and i want diff column as an output.I tried with loops iteration.if i am passing array of values and i want diff column array.

 l                h              diff           
 100.87           100.87         max(h-l)

99.800778         100.87         max ((h-l),diff[0])

101.1281283     101.1281283      max ((h-l),diff[1])     

106.4575807     106.4575807      max ((h-l),diff[2])

109.3212896     109.3212896        .....

107.7907916     109.3212896

105.128359      109.3212896

103.8668187     109.3212896

108.9978396     109.3212896

110.0006197     110.0006197

Can someone help me out.

Sudheesh Singanamalla
  • 2,283
  • 3
  • 19
  • 36
Pratham
  • 101
  • 1
  • 9
  • For future reference: [How to create good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – pault Feb 15 '18 at 16:24

1 Answers1

3

IIUC, you need cummax:

df['diff'] = df['h'] - df['l']
df['diff'] = df['diff'].cummax()

You can do this in one line:

df['diff'] = (df['h'] - df['l']).cummax()

Output:

            l           h      diff
0  100.870000  100.870000  0.000000
1   99.800778  100.870000  1.069222
2  101.128128  101.128128  1.069222
3  106.457581  106.457581  1.069222
4  109.321290  109.321290  1.069222
5  107.790792  109.321290  1.530498
6  105.128359  109.321290  4.192931
7  103.866819  109.321290  5.454471
8  108.997840  109.321290  5.454471
9  110.000620  110.000620  5.454471
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • @Pratham Did this solution help you? Would you consider [accepting](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work?answertab=votes#tab-top). – Scott Boston Feb 22 '18 at 22:02