Home > Backend Development > Python Tutorial > How Can I Replace NaN Values in a Pandas DataFrame Column?

How Can I Replace NaN Values in a Pandas DataFrame Column?

Mary-Kate Olsen
Release: 2024-12-14 21:56:12
Original
616 people have browsed it

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]
})
Copy after login

To replace the NaN values in the "Amount" column with a specific value, use fillna():

df["Amount"] = df["Amount"].fillna(0)
Copy after login

Alternatively, you can pass a dictionary with the desired replacement values for specific columns:

df = df.fillna({
    "Amount": 0
})
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template