Python——如何从 Pandas DataFrame 中删除 null 行
若要删除 Pandas DataFrame 中的 null 行,可使用 dropna() 方法。假设以下为 CSV 文件的一部分,其中有一些 NaN,即 null 值 −
让我们使用 read_csv() 来读取该 CSV 文件。我们的 CSV 文件位于桌面 −
dataFrame = pd.read_csv("C:\Users\amit_\Desktop\CarRecords.csv")
使用 dropna() 来删除 null 值 −
dataFrame = dataFrame.dropna()
示例
以下为完整代码 −
import pandas as pd # reading csv file dataFrame = pd.read_csv("C:\Users\amit_\Desktop\CarRecords.csv") print("DataFrame...\n",dataFrame) # count the rows and columns in a DataFrame print("\nNumber of rows and column in our DataFrame = ",dataFrame.shape) dataFrame = dataFrame.dropna() print("\nDataFrame after removing null values...\n",dataFrame) print("\n(Updated) Number of rows and column in our DataFrame = ",dataFrame.shape)
输出
将生成以下输出 −
DataFrame... Car Place UnitsSold 0 Audi Bangalore 80.0 1 Porsche Mumbai 110.0 2 RollsRoyce Pune NaN 3 BMW Delhi 200.0 4 Mercedes Hyderabad 80.0 5 Lamborghini Chandigarh NaN 6 Audi Mumbai NaN 7 Mercedes Pune 120.0 8 Lamborghini Delhi 100.0 Number of rows and column in our DataFrame = (9, 3) DataFrame after removing null values... Car Place UnitsSold 0 Audi Bangalore 80.0 1 Porsche Mumbai 110.0 3 BMW Delhi 200.0 4 Mercedes Hyderabad 80.0 7 Mercedes Pune 120.0 8 Lamborghini Delhi 100.0 (Updated) Number of rows and column in our DataFrame = (6, 3)
广告