Python - 从 DataFrame 中删除缺失(NaN)值


要移除缺失值(即 NaN 值),请使用 dropna() 方法。首先,让我们导入必要的库 −

import pandas as pd

读取 CSV 并创建一个 DataFrame −

dataFrame = pd.read_csv("C:\Users\amit_\Desktop\CarRecords.csv")

使用 dropna() 删除缺失值。在使用 dropna() 后,NaN 将显示为缺失值 −

dataFrame.dropna()

示例

以下是完整代码

import pandas as pd

# reading csv file
dataFrame = pd.read_csv("C:\Users\amit_\Desktop\CarRecords.csv")
print("DataFrame with some NaN (missing) values...\n",dataFrame)

# count the rows and columns in a DataFrame
print("\nNumber of rows and column in our DataFrame = ",dataFrame.shape)

# drop the missing values
print("\nDataFrame after removing NaN values...\n",dataFrame.dropna())

输出

它将显示以下输出 −

DataFrame with some NaN (missing) values...
          Car        Place   UnitsSold
0        Audi    Bangalore        80.0
1     Porsche       Mumbai         NaN
2  RollsRoyce         Pune       100.0
3         BMW        Delhi         NaN
4     Mercedes   Hyderabad        80.0
5  Lamborghini  Chandigarh        80.0
6         Audi      Mumbai         NaN
7     Mercedes        Pune       120.0
8  Lamborghini       Delhi       100.0

Number of rows and colums in our DataFrame = (9, 3)

DataFrame after removing NaN values ...
           Car       Place   UnitsSold
0         Audi   Bangalore        80.0
2   RollsRoyce        Pune       100.0
4     Mercedes   Hyderabad        80.0
5  Lamborghini  Chandigarh        80.0
7     Mercedes        Pune       120.0
8  Lamborghini       Delhi       100.0

更新时间:2021-09-27

2K+ 浏览量

开启你的 职业之旅

通过完成课程获得认证

开始
广告