Skip to content
Advertisement

If value is greater than the previous replace with previous in Pandas

I am working on a data processing script that does some basic calcs from data files and sorts the data. The last piece to the puzzle is identifying if the next value is > the previous and if it is replace the next value with the previous.

My df is set up as this:

Date        Minimum Z
2020-06-30  6550
2020-07-31  6600
2020-08-31  6550
2020-09-30  6540
2020-10-31  6530

I want the program to identify that the 6600 value is greater than the 6550. Once identified it should replace that 6600 with 6550 and continue over the entire df. I have done something similar, but it was for specific values like NAN or zeros. Anyways below is what I need the df to be transformed to:

    Date        Minimum Z
    2020-06-30  6550
    2020-07-31  6550
    2020-08-31  6550
    2020-09-30  6540
    2020-10-31  6530

Any help would be appreciated!

Advertisement

Answer

I was able to solve my question pretty simply.

df['min z'] = df5['Minimum Z'].expanding().apply(min)
df = df5.drop(columns=['Minimum Z'])

Which outputs:

    Date            min z
0   2020-06-30  6550.000000
1   2020-07-31  6550.000000
2   2020-08-31  6550.000000
3   2020-09-30  6540.577164
4   2020-10-31  6530.831152
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement