Удалить строки из фрейма данных Pandas с отсутствующими значениями или NaN в столбцах
Pandas предоставляет различные структуры данных и операции для управления числовыми данными и временными рядами. Однако могут быть случаи, когда некоторые данные могут отсутствовать. В Pandas отсутствующие данные представлены двумя значениями:
- Нет: Нет - это одноэлементный объект Python, который часто используется для отсутствия данных в коде Python.
- NaN: NaN (аббревиатура от Not a Number) - это специальное значение с плавающей запятой, распознаваемое всеми системами, которые используют стандартное представление с плавающей запятой IEEE.
Pandas treat None and NaN as essentially interchangeable for indicating missing or null values. In order to drop a null values from a dataframe, we used dropna() function this function drop Rows/Columns of datasets with Null values in different ways.
Syntax:
DataFrame.dropna(axis=0, how=’any’, thresh=None, subset=None, inplace=False)Parameters:
axis: axis takes int or string value for rows/columns. Input can be 0 or 1 for Integer and ‘index’ or ‘columns’ for String.
how: how takes string value of two kinds only (‘any’ or ‘all’). ‘any’ drops the row/column if ANY value is Null and ‘all’ drops only if ALL values are null.
thresh: thresh takes integer value which tells minimum amount of na values to drop.
subset: It’s an array which limits the dropping process to passed rows/columns through list.
inplace: It is a boolean which makes the changes in data frame itself if True.
Код №1: удаление строк с хотя бы одним нулевым значением.
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {"First Score":[100, 90, np.nan, 95], "Second Score": [30, np.nan, 45, 56], "Third Score":[52, 40, 80, 98], "Fourth Score":[np.nan, np.nan, np.nan, 65]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) df |

Now we drop rows with at least one Nan value (Null value)
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {"First Score":[100, 90, np.nan, 95], "Second Score": [30, np.nan, 45, 56], "Third Score":[52, 40, 80, 98], "Fourth Score":[np.nan, np.nan, np.nan, 65]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) # using dropna() function df.dropna() |
Output:
Code #2: Dropping rows if all values in that row are missing.
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {"First Score":[100, np.nan, np.nan, 95], "Second Score": [30, np.nan, 45, 56], "Third Score":[52, np.nan, 80, 98], "Fourth Score":[np.nan, np.nan, np.nan, 65]} # creating a dataframe from dictionarydf = pd.DataFrame(dict) df |

Now we drop a rows whose all data is missing or contain null values(NaN)
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {"First Score":[100, np.nan, np.nan, 95], "Second Score": [30, np.nan, 45, 56], "Third Score":[52, np.nan, 80, 98], "Fourth Score":[np.nan, np.nan, np.nan, 65]} df = pd.DataFrame(dict) # using dropna() function df.dropna(how = "all") |
Выход:
Code #3: Dropping columns with at least 1 null value.
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {"First Score":[100, np.nan, np.nan, 95], "Second Score": [30, np.nan, 45, 56], "Third Score":[52, np.nan, 80, 98], "Fourth Score":[60, 67, 68, 65]} # creating a dataframe from dictionary df = pd.DataFrame(dict) df |

Now we drop a columns which have at least 1 missing values
# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # dictionary of listsdict = {"First Score":[100, np.nan, np.nan, 95], "Second Score": [30, np.nan, 45, 56], "Third Score":[52, np.nan, 80, 98], "Fourth Score":[60, 67, 68, 65]} # creating a dataframe from dictionary df = pd.DataFrame(dict) # using dropna() function df.dropna(axis = 1) |
Выход :
Код №4: Удаление строк с хотя бы одним нулевым значением в CSV-файле.
Note: In this, we are using CSV file, to download the CSV file used, Click Here.
# importing pandas module import pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # making new data frame with dropped NA values new_data = data.dropna(axis = 0, how ="any") new_data |
Output:
Now we compare sizes of data frames so that we can come to know how many rows had at least 1 Null value
print("Old data frame length:", len(data))print("New data frame length:", len(new_data)) print("Number of rows with at least 1 NA value: ", (len(data)-len(new_data))) |
Выход :
Длина старого кадра данных: 1000 Длина нового кадра данных: 764 Количество строк с хотя бы одним значением NA: 236
Поскольку разница составляет 236, было 236 строк, которые имели по крайней мере 1 значение NULL в любом столбце.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.