To count the NaN occurrences in a column, use the isna(). Use the sum() to add the values and find the count.
At first, let us import the required libraries with their respective aliases −
import pandas as pd import numpy as np
Create a DataFrame. We have set the NaN values using the Numpy np.inf in “Units_Sold” column −
dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, np.NaN, 150, np.NaN, 200, np.NaN] })
Count NaN values from column "Units_Sold" −
dataFrame["Units_Sold"].isna().sum()
Example
Following is the code −
import pandas as pd import numpy as np # creating dataframe dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, np.NaN, 150, np.NaN, 200, np.NaN] }) print("Dataframe...\n",dataFrame) # count NaN values from column "Units_Sol" count = dataFrame["Units_Sold"].isna().sum() print("\nCount of NaN values in column Units_Sold...\n",count)
Output
This will produce the following output −
Dataframe... Car Cubic_Capacity Reg_Price Units_Sold 0 BMW 2000 7000 100.0 1 Lexus 1800 1500 NaN 2 Tesla 1500 5000 150.0 3 Mustang 2500 8000 NaN 4 Mercedes 2200 9000 200.0 5 Jaguar 3000 6000 NaN Count of NaN values in column Units_Sold... 3