
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements