Featured Post

Top Questions People Ask About Pandas, NumPy, Matplotlib & Scikit-learn — Answered!

Image
 Whether you're a beginner or brushing up on your skills, these are the real-world questions Python learners ask most about key libraries in data science. Let’s dive in! 🐍 🐼 Pandas: Data Manipulation Made Easy 1. How do I handle missing data in a DataFrame? df.fillna( 0 ) # Replace NaNs with 0 df.dropna() # Remove rows with NaNs df.isna(). sum () # Count missing values per column 2. How can I merge or join two DataFrames? pd.merge(df1, df2, on= 'id' , how= 'inner' ) # inner, left, right, outer 3. What is the difference between loc[] and iloc[] ? loc[] uses labels (e.g., column names) iloc[] uses integer positions df.loc[ 0 , 'name' ] # label-based df.iloc[ 0 , 1 ] # index-based 4. How do I group data and perform aggregation? df.groupby( 'category' )[ 'sales' ]. sum () 5. How can I convert a column to datetime format? df[ 'date' ] = pd.to_datetime(df[ 'date' ]) ...

How to Fill Nulls in Pandas: bfill and ffill

In Pandas, bfill and ffill are two important methods used for filling missing values in a DataFrame or Series by propagating the previous (forward fill) or next (backward fill) valid values respectively. These methods are particularly useful when dealing with time series data or other ordered data where missing values need to be filled based on the available adjacent values.


Bfill and Ffill methods


ffill (forward fill):

When you use the ffill method on a DataFrame or Series, it fills missing values with the previous non-null value in the same column. It propagates the last known value forward.

This method is often used to carry forward the last observed value for a specific column, making it a good choice for time series data when the assumption is that the value doesn't change abruptly.

Example:


import pandas as pd


data = {'A': [1, 2, None, 4, None, 6],

        'B': [None, 'X', 'Y', None, 'Z', 'W']}


df = pd.DataFrame(data)

print(df)

# Output:

#      A     B

# 0  1.0  None

# 1  2.0     X

# 2  NaN     Y

# 3  4.0  None

# 4  NaN     Z

# 5  6.0     W


# Forward fill missing values

df_filled = df.ffill()

print(df_filled)

# Output:

#      A     B

# 0  1.0  None

# 1  2.0     X

# 2  2.0     Y

# 3  4.0     Y

# 4  4.0     Z

# 5  6.0     W


bfill (backward fill):

The bfill method fills missing values with the next non-null value in the same column. It propagates the next known value backward.

Like ffill, this method can be useful in time series data, especially when values are missing at the beginning of the dataset.

Example:


import pandas as pd


data = {'A': [None, 2, None, 4, 5, None],

        'B': ['X', 'Y', None, None, 'Z', None]}


df = pd.DataFrame(data)

print(df)

# Output:

#      A     B

# 0  NaN     X

# 1  2.0     Y

# 2  NaN  None

# 3  4.0  None

# 4  5.0     Z

# 5  NaN  None


# Backward fill missing values

df_filled = df.bfill()

print(df_filled)

# Output:

#      A     B

# 0  2.0     X

# 1  2.0     Y

# 2  4.0  None

# 3  4.0     Z

# 4  5.0     Z

# 5  NaN  None

These methods can be very useful for handling missing data when the order of the data is important, such as in time series analysis.

Comments

Popular posts from this blog

SQL Query: 3 Methods for Calculating Cumulative SUM

5 SQL Queries That Popularly Used in Data Analysis

Big Data: Top Cloud Computing Interview Questions (1 of 4)