﻿ Pandas: Replace current value in a dataframe column based on last largest value - 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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Python: Tips of the Day

Inserting if statements using conditional list comprehensions:

```x = [1, 2, 3, 4, 5, 6]
result = []
for idx in range(len(x)):
if x[idx] % 2 == 0:
result.append(x[idx] * 2)
else:
result.append(x[idx])
result
```

Output:

```[1, 4, 3, 8, 5, 12]
```
`[(element * 2 if element % 2 == 0 else element) for element in x]`

Output:

```[1, 4, 3, 8, 5, 12]
```
`[element * 2 for element in x if element % 2 == 0]`

Output:

```[4, 8, 12]
```