python fillna
fillna is a method in pandas, a Python library for data manipulation and analysis, which is used to fill missing or null values in a DataFrame or Series object with a specified value or method.
The basic syntax for fillna() method is as follows:
DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)
Some of the commonly used parameters of fillna() method are:
-
value: It is used to specify the value to be used for filling the missing values. It can be a scalar value, dictionary, or a Series object.
-
method: It is used to specify the method to be used for filling the missing values. It can take values like 'ffill' or 'pad' to fill forward, 'bfill' or 'backfill' to fill backward, or 'nearest' to fill with the nearest value.
-
axis: It is used to specify the axis along which to fill the missing values. It can be 0 for rows or 1 for columns.
-
inplace: It is used to specify whether to modify the original DataFrame or create a new one.
-
limit: It is used to specify the maximum number of consecutive missing values to be filled.
-
downcast: It is used to specify the data type to which the filled values should be downcasted.
Here's an example of how to use fillna() method in pandas:
import pandas as pd
create a sample DataFrame with missing values
df = pd.DataFrame({'A': [1, 2, None, 4], 'B': [5, None, 7, None], 'C': [None, 9, None, 11]})
fill missing values with a scalar value
df.fillna(0, inplace=True)
fill missing values with the mean value of each column
df.fillna(df.mean(), inplace=True)
fill missing values with the previous value in the same column
df.fillna(method='ffill', inplace=True)
fill missing values with the next value in the same column
df.fillna(method='bfill', inplace=True)
fill missing values with the nearest value in the same column
df.fillna(method='nearest', inplace=True)
原文地址: https://www.cveoy.top/t/topic/bVKF 著作权归作者所有。请勿转载和采集!