Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16506

Keep the previous maximum value and create a new column [duplicate]

$
0
0

This is my DataFrame:

import pandas as pddf = pd.DataFrame(    {'a': [1, 9, 8, 10, 7, 11, 20]    })

And this is the output that I want. I want to create column b:

    a   b0   1   11   9   92   8   93  10  104   7  105  11  116  20  20

This is actually a problem when I am converting code from Pine Script to Python. I am not used to thinking in this way.

I explain the issue with an example:

Row 0 in b is always df.a.iloc[0]. Now in order to get the next row in b, row number 1 in a should be compared with row number 0 in b. The greater one is selected for b. In this case 9 > 1 so 9 is selected.

For next row in b row number 2 in a is compared with row number 1 in b. 9 > 8 so 9 is selected. And it goes to the end. This image clarifies the issue:

enter image description here

I tried a lot of solutions. But, since I am not used to this kind of logic, It feels like I'm running in circles. This is one of my attempts:

df["b"] = np.fmax(df["a"], df["a"].shift(1))

Viewing all articles
Browse latest Browse all 16506

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>