Python - Replace negative values with latest preceding positive value in Pandas DataFrame


We want to replace the negative values with latest preceding positive value. With that, if there’s no positive preceding value, then the value should update to 0.

Input

For example, the input is −

DataFrame:  
One  two
0  -2   -3
1   4   -7
2   6    5
3   0   -9

Output

The output should be −

   One two
0   0   0
1   7   0
2   4   2
3   0   2

Data Frame masking is used to replace negative values. To fill the missing values, we used forward fill. At first, let us create pandas dataframe −

# create pandas dataframe
df = pd.DataFrame({'One': [-3, 7, 4, 0], 'two': [-6, -1, 2, -8]})

Let us perform masking −

df = df.mask(df.lt(0)).ffill().fillna(0).astype('int32')

Example

Following is the code −

import pandas as pd

# create pandas dataframe
df = pd.DataFrame({'One': [-3, 7, 4, 0],'two': [-6, -1, 2, -8]})

# displaying the DataFrame
print"DataFrame: \n",df

# masking
df = df.mask(df.lt(0)).ffill().fillna(0).astype('int32')

# displaying the updated DataFrame
print"\nUpdated DataFrame: \n",df

Output

This will produce the following output −

DataFrame:
   One   two
0   -3   -6
1    7   -1
2    4    2
3    0   -8
Updated DataFrame:
   One   two
0    0    0
1    7    0
2    4    2
3    0    2


Updated on: 09-Sep-2021

575 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements