How to use the fillna function in Python.
The fillna function is a method in the pandas library that is used to fill missing values (NaN) or replace specified values.
Common use cases of the fillna() method are as follows:
- Fill in missing values with a specified value.
df.fillna(value)
This method fills missing values with a specified value.
- Fill using the previous non-missing value.
df.fillna(method='ffill')
This method fills missing values with the previous non-missing value.
- Fill using the next non-missing value:
df.fillna(method='bfill')
This method fills missing values with the following non-missing value.
- Fill missing values in a specified column:
df[column_name].fillna(value)
This method will fill missing values in the specified column_name with the specified value.
- Fill the specified column with the previous non-missing value.
df[column_name].fillna(method='ffill')
This method fills missing values in the specified column, column_name, with the previous non-missing value.
- Fill the specified column with the next non-missing value.
df[column_name].fillna(method='bfill')
This method fills missing values in the specified column, column_name, with the next non-missing value.
In addition to the common uses mentioned above, the fillna() method can also accept other parameters such as inplace and limit, which are used to specify the fill method and limit the number of fillings.
Note: The fillna() method does not alter the original DataFrame, instead it returns a new DataFrame with the filled values. If you want to modify the original DataFrame, you can use the parameter inplace=True.