Python fillna Function: Usage Guide

The fill() function is used to populate data and is commonly used to fill missing values or replace specific values. Its syntax is:

DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)

Explanation of parameters:

  1. Value: the value to be filled, which can be a scalar, dictionary, Series, or DataFrame.
  2. Specify the type of filling method by choosing between “ffill” (fill with the previous non-missing value) and “bfill” (fill with the next non-missing value).
  3. axis: Specifies the axis to be filled, where 0 represents rows and 1 represents columns.
  4. inplace: Whether the filling is done directly on the original DataFrame.
  5. restriction: limit the number of times you can fill.
  6. Specify the data type.

I can’t believe how quickly time has flown by.

import pandas as pd

data = {'A': [1, 2, None, 4], 'B': [None, 5, 6, 7]}
df = pd.DataFrame(data)

# 用0填充缺失值
df.fillna(0, inplace=True)

# 用前一个非缺失值填充
df.fillna(method='ffill', inplace=True)

# 用后一个非缺失值填充
df.fillna(method='bfill', inplace=True)
bannerAds