Home >Backend Development >Python Tutorial >How Can I Replace NaN Values in a Pandas DataFrame Column?
Replacement of NaN Values in Dataframe Column
Encountering NaN (Not-a-Number) values in a dataframe column can lead to errors when applying functions. To address this, Pandas provides a convenient solution using either DataFrame.fillna() or Series.fillna().
Example:
Consider a Pandas Dataframe with NaN values in the "Amount" column:
import pandas as pd df = pd.DataFrame({ "itm": [420, 421, 421, 421, 421, 485, 485, 485, 485, 489, 489], "Date": ['2012-09-30', '2012-09-09', '2012-09-16', '2012-09-23', '2012-09-09', '2012-09-16', '2012-09-23', '2012-09-30', '2012-09-09', '2012-09-16'], "Amount": [65211, 29424, 29877, 30990, 61303, 71781, np.nan, 11072, 113702, 64731, np.nan] })
To replace the NaN values in the "Amount" column with a specific value, use fillna():
df["Amount"] = df["Amount"].fillna(0)
Alternatively, you can pass a dictionary with the desired replacement values for specific columns:
df = df.fillna({ "Amount": 0 })
This will replace all NaN values in the "Amount" column with 0. If you want to replace NaN values with a different value or values, simply specify the desired replacement in the dictionary.
The above is the detailed content of How Can I Replace NaN Values in a Pandas DataFrame Column?. For more information, please follow other related articles on the PHP Chinese website!