w3resource

Pandas: Replace current value in a dataframe column based on last largest value

Pandas: DataFrame Exercise-78 with Solution

Write a Pandas program to replace the current value in a dataframe column based on last largest value. If the current value is less than last largest value replaces the value with 0.

Test data: rnum
0 23
1 21
2 27
3 22
4 34
5 33
6 34
7 31
8 25
9 22
10 34
11 19
12 31
13 32
14 19

Sample Solution :

Python Code :

import pandas as pd
df1=pd.DataFrame({'rnum':[23, 21, 27, 22, 34, 33, 34, 31, 25, 22, 34, 19, 31, 32, 19]})
print("Original DataFrame:")
print(df1)
df1['rnum']=df1.rnum.where(df1.rnum.eq(df1.rnum.cummax()),0)
print("\nReplace current value in a dataframe column based on last largest value:")
print(df1)

Sample Output:

Original DataFrame:
    rnum
0     23
1     21
2     27
3     22
4     34
5     33
6     34
7     31
8     25
9     22
10    34
11    19
12    31
13    32
14    19

Replace current value in a dataframe column based on last largest value:
    rnum
0     23
1      0
2     27
3      0
4     34
5      0
6     34
7      0
8      0
9      0
10    34
11     0
12     0
13     0
14     0

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous:Write a Pandas program to get the numeric representation of an array by identifying distinct values of a given column of a dataframe.
Next: Write a Pandas program to create a DataFrame from the clipboard (data from an Excel spreadsheet or a Google Sheet).

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/python-pandas-data-frame-exercise-78.php