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

Replacing a value with its previous value in a column if it is greater

$
0
0

This is my dataframe:

import pandas as pddf = pd.DataFrame(    {'a': [101, 90, 11, 120, 1]    })

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

     a    y0  101    101.01   90    101.02   11    90.03  120    120.04    1    120.0

Basically values in a are compared with their previous value. And the greater one is selected.

For example for row 1, 90 is compared with 101. 101 is greater so it is selected.

I have done it in this way:

df['x'] = df.a.shift(1)df['y'] = df[['a', 'x']].max(axis=1)

Is there a cleaner or some kind of built-in way to do it?


Viewing all articles
Browse latest Browse all 13981

Trending Articles