Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data preprocessing
  • Data Manipulation
  • Data Analysis using Pandas
  • EDA
  • Pandas Exercise
  • Pandas AI
  • Numpy
  • Matplotlib
  • Plotly
  • Data Analysis
  • Machine Learning
  • Data science
Open In App
Next Article:
Python Pandas: Replace Zeros with Previous Non-Zero Value
Next article icon

Python Pandas: Replace Zeros with Previous Non-Zero Value

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with a dataset, it's common to encounter zeros that need to be replaced with non-zero values. This situation arises in various contexts, such as financial data, sensor readings, or any dataset where a zero might indicate missing or temporary invalid data. Python's Pandas library provides efficient ways to handle this task.

We can replace zeros with Mean, Median, and Mode, or perform some calculations to replace them with non-zero values. In this article, we will learn how to replace zeros with the previous non-zero value in a DataFrame.

Learning Objectives

By the end of this article, we will learn:

  • How to load and inspect data using Pandas.
  • How to identify and handle zero values in a DataFrame.
  • Different methods to replace zeros with the previous non-zero value.
  • Practical examples of these methods applied to time series data.

Prerequisites

To follow along with the examples in this article, we should have:

  • Familiarity with the Pandas library.
  • Pandas installed in the Python environment. If not, we can install it using:
pip install pandas

Step 1: Loading and Inspecting Data

Let's start by creating a simple Pandas DataFrame that contains zero values, which we will replace with the previous non-zero value.

Python
import pandas as pd  # Sample DataFrame data = {     'Date': ['2024-01-01', '2024-01-02',              '2024-01-03', '2024-01-04',              '2024-01-05', '2024-01-06',              '2024-01-07', '2024-01-08',              '2024-01-09', '2024-01-10'],     'Value': [10, 4, 0, 0, 30, 0, 7, 0, 0, 0] }  df = pd.DataFrame(data) df['Date'] = pd.to_datetime(df['Date'])  print(df) 

Output

Screenshot-2024-09-05-121218
Pandas Dataframe

This DataFrame represents a time series where some values are zero. The goal is to replace these zeros with the most recent non-zero value.

Step 2: Using the ffill() Method

One of the simplest ways to replace zeros with the previous non-zero value is to temporarily convert zeros to NaN (Not a Number), and then use the ffill() method to propagate the last valid observation forward.

Explanation:

  • replace(0, pd.NA): Converts all zeros to NaN.
  • ffill(): Uses the forward fill method to replace NaN values with the last valid observation.
Python
df['Value'] = df['Value'].replace(0, pd.NA).ffill() print(df) 

Output

Screenshot-2024-09-05-121634
pandas ffill() method


Step 3: Using where() and shift() Methods

Another approach is to use the where() function in combination with shift() to conditionally replace values.

Explanation:

  • where(df['Value'] != 0): Keeps values where the condition is true.
  • df['Value'].shift(): Shifts the values in the column down by one position. The where condition replaces zeros with the shifted values.
Python
df['Value'] = df['Value'].where(df['Value'] != 0, df['Value'].shift()) print(df) 

Output

Screenshot-2024-09-05-121634
where() and shift() method in Pandas


Step 4: Using replace() method

To replace zeros with the previous non-zero value, we can use the replace method.

Python
# Replace zeros with the previous non-zero value df['Value'].replace(to_replace=0, method='ffill', inplace=True)  print(df) 

Output

Screenshot-2024-09-05-121634
Using pandas replace() method

The 'method' keyword in Series.replace is deprecated and will be removed in a future version.

We can modify the above method as per the latest update.

Step 5 Handling Edge Cases - Starting with Zero

If our data starts with one or more zeros, those cannot be replaced by any preceding value since there is none. We may want to decide on a strategy for handling these cases, such as leaving them as zeros or replacing them with a specific value.

Python
import pandas as pd  # Example DataFrame with leading zeros data = {'Value': [0, 0, 0, 1, 0, 3, 0, 0, 5, 0]} df = pd.DataFrame(data)  # Replace zeros with the previous non-zero value, # and fill leading zeros with the first non-zero value df['Value'] = df['Value'].replace(0, pd.NA).ffill() df['Value'] = df['Value'].replace(0, pd.NA).bfill()  print(df) 

Output

Screenshot-2024-09-05-124404
Starting with zeros

Explanation:

  • replace(0, pd.NA).ffill(): This will replace all zeros with the last non-zero value before them. However, if the series starts with zeros, they won't be replaced because there's no previous non-zero value.
  • replace(0, pd.NA).bfill(): After forward filling, this step will replace any remaining zeros (like those at the start of the series) with the next non-zero value in the series.

Conclusion

Replacing zeros with the previous non-zero value in a pandas DataFrame is a common data cleaning task that can be easily handled using methods like ffill or apply. By following the steps in this guide, we can efficiently clean our data and prepare it for further analysis, ensuring that zeros don't distort our results or insights.


Next Article
Python Pandas: Replace Zeros with Previous Non-Zero Value

M

monkserndp4
Improve
Article Tags :
  • Python
  • Python-pandas
Practice Tags :
  • python

Similar Reads

    Python | Replace negative value with zero in numpy array
    Given numpy array, the task is to replace negative value with zero in numpy array. Let’s see a few examples of this problem. Method #1: Naive Method Python3 # Python code to demonstrate # to replace negative value with 0 import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing init
    4 min read
    Replace NaN Values with Zeros in Pandas DataFrame
    NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to
    5 min read
    Replace NaN with zero and fill negative infinity values in Python
    In this article, we will cover how to replace NaN with zero and fill negative infinity values in Python using NumPy. Example Input: [ nan -inf   5.] Output: [0.00000e+00 9.99999e+05 5.00000e+00] Explanation: Replacing NaN with 0 and negative inf with any value. numpy.nan_to_num method The numpy.nan_
    3 min read
    Python | Pandas Series.replace()
    Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.replace() function is used to
    3 min read
    Pandas Replace Multiple Values in Python
    Replacing multiple values in a Pandas DataFrame or Series is a common operation in data manipulation tasks. Pandas provides several versatile methods for achieving this, allowing you to seamlessly replace specific values with desired alternatives. In this context, we will explore various approaches
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences