Python - 如何计算 Pandas 数据框中某一列的 NaN 出现次数?
要计算某一列中 NaN 的出现次数,请使用 isna()。使用 sum() 加上这些值并找出次数。
首先,让我们使用其各自的别名导入所需的库 −
import pandas as pd import numpy as np
创建一个数据框。我们使用 Numpy np.inf 在 “Units_Sold” 列中设置了 NaN 值 −
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] })
从列 "Units_Sold" 中计算 NaN 值 −
dataFrame["Units_Sold"].isna().sum()
示例
代码如下 −
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)
输出
这将产生以下输出 −
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
广告