I have a dataframe, and I want every value in a specific column to be greater or equal to the previous value.
In the example below, I want it to be applied on column 'd', so the expected result should replace 5 with 7.
So how can I do it?
The actual situation needs to consider efficiency issues, it is best not to use FOR.
Thank you in advance for your reply.
code:
>>> df = pd.DataFrame({'a': [1,3,2,5], 'b': [2, 4,3,4], 'c':[3,5,4,3]})
>>> df
a b c
0 1 2 3
1 3 4 5
2 2 3 4
3 5 4 3
>>> df['d'] = df['a']+df['b']
>>> df
a b c d
0 1 2 3 3
1 3 4 5 7
2 2 3 4 5
3 5 4 3 9
You can do this using cummax
:
>>> df['d'] = df['d'].cummax()
>>> df
a b c d
0 1 2 3 3
1 3 4 5 7
2 2 3 4 7
3 5 4 3 9
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.