Replace all the NaN values with Zero's in a column of a Pandas dataframe

Replace all the NaN values with Zero's in a column of a Pandas dataframe

To replace all the NaN (Not a Number) values with zeros in a specific column of a pandas DataFrame, you can use the fillna() method. Here's how you can do it:

  1. Setup: First, ensure you have pandas installed:

    pip install pandas 
  2. Sample Code:

    import pandas as pd import numpy as np # Sample DataFrame data = { 'A': [1, 2, np.nan, 4], 'B': [5, np.nan, 7, 8], 'C': [9, 10, 11, 12] } df = pd.DataFrame(data) print("Before replacing NaN values:") print(df) # Replace NaN values in column 'B' with 0 df['B'] = df['B'].fillna(0) print("\nAfter replacing NaN values:") print(df) 

    Output:

    Before replacing NaN values: A B C 0 1.0 5.0 9 1 2.0 NaN 10 2 NaN 7.0 11 3 4.0 8.0 12 After replacing NaN values: A B C 0 1.0 5.0 9 1 2.0 0.0 10 2 NaN 7.0 11 3 4.0 8.0 12 

If you want to replace NaN values in all columns with zeros, you can simply use:

df.fillna(0, inplace=True) 

This will modify the DataFrame in-place and replace all NaN values with zeros across all columns.


More Tags

recursion option-type android-listview listviewitem pyodbc dummy-variable dotnet-httpclient npm-link opencsv scjp

More Programming Guides

Other Guides

More Programming Examples