Pandas: Replace current value in a dataframe column based on last largest value
78. Replace Value Based on Last Largest Value
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 :
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
For more Practice: Solve these Related Problems:
- Write a Pandas program to iterate through a column and replace any value lower than the maximum seen so far with zero.
- Write a Pandas program to update a column such that if the current value is less than the previous maximum, it is set to a default value.
- Write a Pandas program to compare each value with the cumulative maximum of the column and then replace values that do not meet the criterion.
- Write a Pandas program to compute the cumulative maximum of a column and then conditionally replace current values based on that maximum.
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.