Обработка пропусков в Pandas
К примеру, можно использовать число -9999 или редко встречающееся сочетание битов. Более часто встречающийся способ — условное обозначение через NaN. NaN — это специальное значение, определенное спецификацией IEEE для чисел с плавающей точкой и используется во многих ЯП.
У метода есть ограничения. Во-первых использование значений индикаторов может привести к дополнительным не оптимизированным расчетам. Во-вторых NaN доступен не для всех типов данных.
Использование масок
Можно создать отдельный булевый массив, индицирующий пропущенные значения. В ряде языков выделяется отдельный бит для разметки пропусков в массиве данных локально. Оба подхода влекут за собой перерасход памяти.
Как это реализовано в Pandas?
Pandas построена на NumPy, в котором отсутствует понятие пропуска для всех данных кроме данных с плавающей точкой. NumPy поддерживает маски, но использование такого подходжа в Pandas влечет значительные накладные расходы на хранение, вычисление и поддержку кода.
В итоге в Pandas используется:
Объект None
None — объект python. Его нельзя использовать в NumPy и во всех производных массивах Pandas. None используется только в массивах с типом object. Когда мы создаем массив, используя None, автоматически создается массив с типом object.
Тип object означает, что NumPy не смог установить тип объектов массива, единственное что он знает — это то, что это объекты python. Операции с такими массивами будут производится на уровне языка python, т.е. со всеми накладными расходами, присущими языку с динамической типизацией. Оптимизация NumPy работать не будет.
Кроме того, функции агрегирования по массиву, например, massive.sum() или massive.min() выбросят ошибку, так как операции между численным значением и значением None не определены
Объект NaN
Объект NaN определяет отсутствие числового значения с плавающей точкой. Это вызывает некоторые проблемы — если NaN попадает в массив, все данные приводятся к числам с плавающей точкой. Кроме того, все операции с NaN приводят к NaN, в том числе и функции агрегирования.
Не забудьте, что для вызова объекта NaN нужен NumPy
Nan и None
Pandas преобразует None в NaN, если оба будут встречены в одном массиве. Естественно, осуществляется и повышающее преобразование с приведением всех непустых числовых значений к числу с плавающей точкой, а всех остальных к NaN.
Правила повышающих преобразований типов в Pandas (строки всегда хранятся как object)
| Typeclass | Conversion When Storing NAN | NAN Sentinel Value |
|---|---|---|
| floating | No change | np.nan |
| object | No change | None or np.nan |
| integer | Cast to float64 | np.nan |
| boolean | Cast to object | None or np.nan |
Операции над пустыми значениями
В Pandas доступно несколько методов:
isnull() — генерирует булеву маску для отсутствующих значений
notnull() — тоже для непустых
dropna() — фильтрация данных по отсутствующим значениям
fillna() — замена пропусков с возвратом копии
Методы доступны как для объектов Series так и для dataFrame (с выбором измерения).
Кроме того, для dropna() ожно задать дополнительные параметры. how=’any’ задан по дефолту, можно переопределить как ‘all’ — будут отбрасываться только полностью пустые строки/столбцы. thresh задает минимальное значение непустых значений, выше которого строки/столбцы не отбрасываются.
Для fillna() доступно несколько аргументов. method=’ffill’ и method=’bfill’ определяют какими значениями будут заполняться пропуски (предыдущими или последующими в массиве).
Все статьи с тегом pandas
-
(25 Jul 2020)
(18 Apr 2020)
(30 Mar 2020)
(04 Mar 2020)
Как понять translating алгоритмы для графов?
Translating алгоритмы (а точнее TransE), рассматриваются в курсе cs224w, про них есть домашка и они фигурируют в нескольких последних лекциях.
Обозначения в анализе алгоритмов
В асимптотическом анализе алгоритмов принято использовать базовые обозначения, позволяющие формализовать сложность алгоритма. Все термины сводятся к устранению постоянных коэффициентов, так.
Working with missing data#
In this section, we will discuss missing (also referred to as NA) values in pandas.
The choice of using NaN internally to denote missing data was largely for simplicity and performance reasons. Starting from pandas 1.0, some optional data types start experimenting with a native NA scalar using a mask-based approach. See here for more.
See the cookbook for some advanced strategies.
Values considered “missing”#
As data comes in many shapes and forms, pandas aims to be flexible with regard to handling missing data. While NaN is the default missing value marker for reasons of computational speed and convenience, we need to be able to easily detect this value with data of different types: floating point, integer, boolean, and general object. In many cases, however, the Python None will arise and we wish to also consider that “missing” or “not available” or “NA”.
If you want to consider inf and -inf to be “NA” in computations, you can set pandas.options.mode.use_inf_as_na = True .
To make detecting missing values easier (and across different array dtypes), pandas provides the isna() and notna() functions, which are also methods on Series and DataFrame objects:
One has to be mindful that in Python (and NumPy), the nan’s don’t compare equal, but None’s do. Note that pandas/NumPy uses the fact that np.nan != np.nan , and treats None like np.nan .
So as compared to above, a scalar equality comparison versus a None/np.nan doesn’t provide useful information.
Integer dtypes and missing data#
Because NaN is a float, a column of integers with even one missing values is cast to floating-point dtype (see Support for integer NA for more). pandas provides a nullable integer array, which can be used by explicitly requesting the dtype:
Alternatively, the string alias dtype=’Int64′ (note the capital "I" ) can be used.
Datetimes#
For datetime64[ns] types, NaT represents missing values. This is a pseudo-native sentinel value that can be represented by NumPy in a singular dtype (datetime64[ns]). pandas objects provide compatibility between NaT and NaN .
Inserting missing data#
You can insert missing values by simply assigning to containers. The actual missing value used will be chosen based on the dtype.
For example, numeric containers will always use NaN regardless of the missing value type chosen:
Likewise, datetime containers will always use NaT .
For object containers, pandas will use the value given:
Calculations with missing data#
Missing values propagate naturally through arithmetic operations between pandas objects.
The descriptive statistics and computational methods discussed in the data structure overview (and listed here and here ) are all written to account for missing data. For example:
When summing data, NA (missing) values will be treated as zero.
If the data are all NA, the result will be 0.
Cumulative methods like cumsum() and cumprod() ignore NA values by default, but preserve them in the resulting arrays. To override this behaviour and include NA values, use skipna=False .
Sum/prod of empties/nans#
This behavior is now standard as of v0.22.0 and is consistent with the default in numpy ; previously sum/prod of all-NA or empty Series/DataFrames would return NaN. See v0.22.0 whatsnew for more.
The sum of an empty or all-NA Series or column of a DataFrame is 0.
The product of an empty or all-NA Series or column of a DataFrame is 1.
NA values in GroupBy#
NA groups in GroupBy are automatically excluded. This behavior is consistent with R, for example:
See the groupby section here for more information.
Cleaning / filling missing data#
pandas objects are equipped with various data manipulation methods for dealing with missing data.
Filling missing values: fillna#
fillna() can “fill in” NA values with non-NA data in a couple of ways, which we illustrate:
Replace NA with a scalar value
Fill gaps forward or backward
Using the same filling arguments as reindexing , we can propagate non-NA values forward or backward:
Limit the amount of filling
If we only want consecutive gaps filled up to a certain number of data points, we can use the limit keyword:
To remind you, these are the available filling methods:
Fill values forward
Fill values backward
With time series data, using pad/ffill is extremely common so that the “last known value” is available at every time point.
ffill() is equivalent to fillna(method=’ffill’) and bfill() is equivalent to fillna(method=’bfill’)
Filling with a PandasObject#
You can also fillna using a dict or Series that is alignable. The labels of the dict or index of the Series must match the columns of the frame you wish to fill. The use case of this is to fill a DataFrame with the mean of that column.
Same result as above, but is aligning the ‘fill’ value which is a Series in this case.
Dropping axis labels with missing data: dropna#
You may wish to simply exclude labels from a data set which refer to missing data. To do this, use dropna() :
An equivalent dropna() is available for Series. DataFrame.dropna has considerably more options than Series.dropna, which can be examined in the API .
Interpolation#
Both Series and DataFrame objects have interpolate() that, by default, performs linear interpolation at missing data points.

Index aware interpolation is available via the method keyword:
For a floating-point index, use method=’values’ :
You can also interpolate with a DataFrame:
The method argument gives access to fancier interpolation methods. If you have scipy installed, you can pass the name of a 1-d interpolation routine to method . You’ll want to consult the full scipy interpolation documentation and reference guide for details. The appropriate interpolation method will depend on the type of data you are working with.
If you are dealing with a time series that is growing at an increasing rate, method=’quadratic’ may be appropriate.
If you have values approximating a cumulative distribution function, then method=’pchip’ should work well.
To fill missing values with goal of smooth plotting, consider method=’akima’ .
These methods require scipy .
When interpolating via a polynomial or spline approximation, you must also specify the degree or order of the approximation:
Compare several methods:

Another use case is interpolation at new values. Suppose you have 100 observations from some distribution. And let’s suppose that you’re particularly interested in what’s happening around the middle. You can mix pandas’ reindex and interpolate methods to interpolate at the new values.
Interpolation limits#
Like other pandas fill methods, interpolate() accepts a limit keyword argument. Use this argument to limit the number of consecutive NaN values filled since the last valid observation:
By default, NaN values are filled in a forward direction. Use limit_direction parameter to fill backward or from both directions.
By default, NaN values are filled whether they are inside (surrounded by) existing valid values, or outside existing valid values. The limit_area parameter restricts filling to either inside or outside values.
Replacing generic values#
Often times we want to replace arbitrary values with other values.
replace() in Series and replace() in DataFrame provides an efficient yet flexible way to perform such replacements.
For a Series, you can replace a single value or a list of values by another value:
You can replace a list of values by a list of other values:
You can also specify a mapping dict:
For a DataFrame, you can specify individual values by column:
Instead of replacing with specified values, you can treat all given values as missing and interpolate over them:
String/regular expression replacement#
Python strings prefixed with the r character such as r’hello world’ are so-called “raw” strings. They have different semantics regarding backslashes than strings without this prefix. Backslashes in raw strings will be interpreted as an escaped backslash, e.g., r’\’ == ‘\\’ . You should read about them if this is unclear.
Replace the ‘.’ with NaN (str -> str):
Now do it with a regular expression that removes surrounding whitespace (regex -> regex):
Replace a few different values (list -> list):
list of regex -> list of regex:
Only search in column ‘b’ (dict -> dict):
Same as the previous example, but use a regular expression for searching instead (dict of regex -> dict):
You can pass nested dictionaries of regular expressions that use regex=True :
Alternatively, you can pass the nested dictionary like so:
You can also use the group of a regular expression match when replacing (dict of regex -> dict of regex), this works for lists as well.
You can pass a list of regular expressions, of which those that match will be replaced with a scalar (list of regex -> regex).
All of the regular expression examples can also be passed with the to_replace argument as the regex argument. In this case the value argument must be passed explicitly by name or regex must be a nested dictionary. The previous example, in this case, would then be:
This can be convenient if you do not want to pass regex=True every time you want to use a regular expression.
Anywhere in the above replace examples that you see a regular expression a compiled regular expression is valid as well.
Numeric replacement#
Replacing more than one value is possible by passing a list.
You can also operate on the DataFrame in place:
Missing data casting rules and indexing#
While pandas supports storing arrays of integer and boolean type, these types are not capable of storing missing data. Until we can switch to using a native NA type in NumPy, we’ve established some “casting rules”. When a reindexing operation introduces missing data, the Series will be cast according to the rules introduced in the table below.
Ordinarily NumPy will complain if you try to use an object array (even if it contains boolean values) instead of a boolean array to get or set values from an ndarray (e.g. selecting values based on some criteria). If a boolean vector contains NAs, an exception will be generated:
However, these can be filled in using fillna() and it will work fine:
pandas provides a nullable integer dtype, but you must explicitly request it when creating the series or column. Notice that we use a capital “I” in the dtype="Int64" .
Experimental NA scalar to denote missing values#
Experimental: the behaviour of pd.NA can still change without warning.
New in version 1.0.0.
Starting from pandas 1.0, an experimental pd.NA value (singleton) is available to represent scalar missing values. At this moment, it is used in the nullable integer , boolean and dedicated string data types as the missing value indicator.
The goal of pd.NA is provide a “missing” indicator that can be used consistently across data types (instead of np.nan , None or pd.NaT depending on the data type).
For example, when having missing values in a Series with the nullable integer dtype, it will use pd.NA :
Currently, pandas does not yet use those data types by default (when creating a DataFrame or Series, or when reading in data), so you need to specify the dtype explicitly. An easy way to convert to those dtypes is explained here .
Propagation in arithmetic and comparison operations#
In general, missing values propagate in operations involving pd.NA . When one of the operands is unknown, the outcome of the operation is also unknown.
For example, pd.NA propagates in arithmetic operations, similarly to np.nan :
There are a few special cases when the result is known, even when one of the operands is NA .
In equality and comparison operations, pd.NA also propagates. This deviates from the behaviour of np.nan , where comparisons with np.nan always return False .
To check if a value is equal to pd.NA , the isna() function can be used:
An exception on this basic propagation rule are reductions (such as the mean or the minimum), where pandas defaults to skipping missing values. See above for more.
Logical operations#
For logical operations, pd.NA follows the rules of the three-valued logic (or Kleene logic, similarly to R, SQL and Julia). This logic means to only propagate missing values when it is logically required.
For example, for the logical “or” operation ( | ), if one of the operands is True , we already know the result will be True , regardless of the other value (so regardless the missing value would be True or False ). In this case, pd.NA does not propagate:
On the other hand, if one of the operands is False , the result depends on the value of the other operand. Therefore, in this case pd.NA propagates:
The behaviour of the logical “and” operation ( & ) can be derived using similar logic (where now pd.NA will not propagate if one of the operands is already False ):
NA in a boolean context#
Since the actual value of an NA is unknown, it is ambiguous to convert NA to a boolean value. The following raises an error:
This also means that pd.NA cannot be used in a context where it is evaluated to a boolean, such as if condition: . where condition can potentially be pd.NA . In such cases, isna() can be used to check for pd.NA or condition being pd.NA can be avoided, for example by filling missing values beforehand.
A similar situation occurs when using Series or DataFrame objects in if statements, see Using if/truth statements with pandas .
NumPy ufuncs#
pandas.NA implements NumPy’s __array_ufunc__ protocol. Most ufuncs work with NA , and generally return NA :
Currently, ufuncs involving an ndarray and NA will return an object-dtype filled with NA values.
The return type here may change to return a different array type in the future.
Conversion#
If you have a DataFrame or Series using traditional types that have missing data represented using np.nan , there are convenience methods convert_dtypes() in Series and convert_dtypes() in DataFrame that can convert data to use the newer dtypes for integers, strings and booleans listed here . This is especially helpful after reading in data sets when letting the readers such as read_csv() and read_excel() infer default dtypes.
In this example, while the dtypes of all columns are changed, we show the results for the first 10 columns.
Работа с отсутствующими значениями в Pandas
Отсутствующее значение в наборе данных отображается как вопросительный знак, ноль, NaN или просто пустая ячейка. Но как можно справиться с недостающими данными?
Конечно, каждая ситуация отличается и должна оцениваться по-разному.
Есть много способов справиться с недостающими значениями. Рассмотрим типичные варианты на примере набора данных — ‘Titanic’. Эти данные являются открытым набором данных Kaggle.
Для анализа необходимо импортировать библиотеки Python и загрузить данные.
Для загрузки используется метод Pandas read.csv(). В скобках указывается путь к файлу в кавычках, чтобы Pandas считывал файл во фрейм данных (Dataframes — df) с этого адреса. Путь к файлу может быть URL адрес или вашим локальным адресом файла.

Показывает первые 2 строки загруженного фрейма данных
Посмотрим на размер данных (количество строк, колонок):
Для просмотра статистической сводки каждого столбца, чтобы узнать распределение данных в каждом столбце используется метод describe( ). Этот метод показывает нам количество строк в столбце — count, среднее значение столбца — mean, столбец стандартное отклонение — std, минимальные (min) и максимальные (max) значения, а также границу каждого квартиля — 25%, 50% и 75%. Любые значения NaN автоматически пропускаются.

метод describe( )
По умолчанию, метод describe( ) пропускает строки и столбцы не содержащие чисел — категориальные признаки. Чтобы включить сводку по всем столбцам нужно в скобках добавить аргумент — include = «all».

метод describe(include = «all»)
Для категориальных признаков этот метод показывает: — Сколько уникальных значений в наборе данных — unique; top значения; частота появления значений — freg.
Метод info( ) — показывает информацию о наборе данных, индекс, столбцы и тип данных, ненулевые значения и использование памяти.

показывает информацию о наборе данных, индекс, столбцы и тип данных, ненулевые значения и использование памяти.
В результате мы видим, что все колонки, кроме колонок ‘Age’, ‘Cabin’ и ‘Embarked’, содержат по 891 строк.
Колонка ‘Survived’ — это целевое значение. Показывает, кто выжил, а кто — нет. Эта колонка заполнена бинарными значениями:
Метод — value_counts(). Подсчет значений — это хороший способ понять, сколько единиц каждой характеристики / переменной у нас есть.

подсчет значений в колонке ‘Survived’
Из 891 пассажира выжило 342.

график подсчет значений в колонке ‘Survived’
Из 891 пассажира выжило 342 это 38%.

График подсчет значений в колонке ‘Survived’
Визуализация: Графики подсчета значений в колонках — «Survived», «Pclass», «Sex», «SibSp», «Parch», «Embarked»

Графики подсчета значений в колонках — «Survived», «Pclass», «Sex», «SibSp», «Parch», «Embarked»
Теперь посмотрим на колонки которые имеют пропущенные значения.
Есть два метода обнаружения недостающих данных: — isnull() и notnull().
Результатом является логическое значение, указывающее, действительно ли значение, переданное в аргумент, отсутствует. «Истина» ( True ) означает, что значение является отсутствующим значением, а «Ложь» ( False ) означает, что значение не является отсутствующим.

True — пропущенные значения
Используя цикл for в Python, мы можем быстро определить количество пропущенных значений в каждом столбце. Как упоминалось выше, «Истина» представляет отсутствующее значение, а «Ложь» означает, что значение присутствует в наборе данных. В теле цикла for метод «.value_counts ()» подсчитывает количество значений «True».
количество пропущенных значений в каждом столбце.
количество пропущенных значений в каждом столбце.
Посмотрим — сколько пропущенных значений в каждой колонке.

количество пропущенных значений в каждом столбце.
В колонке возраст — ‘Age’ не указано 177 значений. И нужно понять — это систематическая ошибка или какая-то случайная погрешность.
Н-р, может у пассажиров 1 класса (или у женщин) не спрашивали про возраст ( т. к. это было не прилично), или случайно пропустили. Понимание о причине пропущенных значений, определит — как работать с этими отсутствующими данными.
Нужно сгруппировать возраст, относительно того, отсутствует возраст или нет. Для группировки используем метод groupby().
True — отсутствует возраст
False — значение заполнено

метод groupby(). True — отсутствует возраст, False — значение заполнено
Среди пассажиров, у которых значение возраста отсутствовало, были выжившие (около 30%) и погибшие (около 70%) — колонка ‘Survived’, True = 0.29 .
Эти пассажиры были в более низком классе:
колонка ‘Pclass’ — True = 2.59 (это среднее значение класса)
колонка ‘Fare’ — True = 22.15 (это среднее значение стоимости билета)
Подсчет значений в колонке ‘Pclass’:

Подсчет значений в колонке ‘Pclass’
Например, в 3 классе было 491 пассажира (это 55%)

Выживаемость пассажиров по классам
Для более детального анализа, создадим новую колонку ‘Age_NaN’ (бинарный классификатор). Используем метод where(), где прописываем условие: — если значение в колонке ‘Age’ отсутствует, то присваиваем в колонке ‘Age_NaN’ — значение 0, если присутствует, то 1.

первые 6 строк фрейма данных с новой колонкой ‘Age_NaN’
Подсчет значений в колонке ‘Age_NaN’

Подсчет значений в колонке ‘Age_NaN’
Выживаемость пассажиров в зависимости от наличия записи о возрасте.

Выживаемость пассажиров в зависимости от наличия записи о возрасте.
И снова мы видим: — что, среди пассажиров, у которых значение возраста отсутствовало, были выжившие (около 30%) и погибшие (около 70%).
Выживаемость пассажиров в зависимости от наличия записи о возрасте и класса.
Выживаемость пассажиров в зависимости от наличия записи о возрасте и класса.
зависимость от наличия записи о возрасте и класса.
В первом классе запись отсутствует у 30 пассажиров. Из 30 пассажиров выжило — 46%(14 пассажиров), погибло — 53%(16 пассажиров). Всего пассажиров было в первом классе — 216 (в данном наборе данных).
Во втором классе запись отсутствует у 11 пассажиров. Из 11 пассажиров выжило — 36%(4 пассажира), погибло — 63% (7 пассажиров). Всего пассажиров было во втором классе — 184 (в данном наборе данных).
В третьем классе запись отсутствует у 136 пассажиров. Из 136 пассажиров выжило — 25% (34 пассажира), погибло — 75% (102 пассажира). Всего пассажиров было в третьем классе — 491 (в данном наборе данных).
Выживаемость пассажиров в зависимости от наличия записи о возрасте и пола.
Выживаемость пассажиров в зависимости от наличия записи о возрасте и пола.
зависимость от наличия записи о возрасте и пола.
У 53 женщин нет записи о возрасте. Из 53 женщин выжило 68% (36 женщин), погибло 32% (17 женщин). Всего женщин было — 314 (в данном наборе данных).
У 124 мужчин нет записи о возрасте. Из 124 мужчин выжило 13% (16 мужчин), погибло 87% (108 мужчин). Всего мужчин было — 577 (в данном наборе данных)
Пассажиров было много в 3 классе и много погибло. Пассажиры — мужчины, у которых был более дешевый билет и более низкий класс — имели меньше шансов выжить.
Т.к. среди пассажиров, у которых значение возраста отсутствовало, были выжившие (около 30%) и погибшие (около 70%), и пассажиры были с разных классов( из 3 класса было значительно больше), и среди пассажиров были мужчины и женщины (мужчин было значительно больше), то при опросе у выживших и при осмотре тел погибших могли случайно пропустить возраст пассажира.
Следовательно делаем вывод, что возраст случайно не занесли.
Решение: Пропущенные значения заполнить средним значением.

график выживаемости пассажиров в зависимости от возраста
Посмотрим на график выживаемости пассажиров в зависимости от класса и возраста

график выживаемости пассажиров в зависимости от класса и возраста
В колонке каюта ( ‘Cabin’) не указано 687 значений. Т. к. пропущенных значений много, можно удалить полностью колонку ‘Cabin’, а можно и оставить отсутствующие данные как — отсутствующие данные. Здесь важно понять: — Существует ли какая-то систематическая взаимосвязь между выживанием и тем, была ли у пассажира отдельная каюта.Для группировки используем метод groupby().
True — отсутствует упоминание о каюте
False — значение заполнено

метод groupby(). True — отсутствует упоминание о каюте, False — значение заполнено
Те, пассажиры у кого запись отсутствует — выжили около 30%. А у кого запись о наличии каюты есть — выжило 67%.
Вывод: Есть взаимосвязь между выживанием и наличием каюты.
Создать новую колонку ‘Cabin_available’ (бинарный классификатор).Используем метод where(), где прописываем условие: — Если значение в колонке ‘Cabin’ отсутствует, то присваиваем в колонке ‘Cabin_available’ — значение 0, если присутствует, то 1.

показывает первые 6 строк фрейма данных с новой колонкой ‘Cabin_available’
Выживаемость пассажиров в зависимости от наличия записи о каюте:
Выживаемость пассажиров в зависимости от наличия записи о каюте
График выживаемости пассажиров в зависимости от наличия записи о каюте
Теперь колонку ‘Cabin’ можно удалить.

фрейм данных без колонки ‘Cabin’
В колонке порт посадки на борт (‘Embarked’) не указано два значения. Это категориальный признак.
Решение: Заменить пропущенные значения по частоте. Заменить отсутствующее значение значением, которым чаще всего встречается в конкретном столбце.

подсчет значений в колонке ‘Embarked’
Чаще всего встречается значение S — 644. Нужно заменить пропущенные значения на S.

метод describe() для колонки ‘Embarked’, после замены пропущенных значений.
Good! Now, we have a dataset with no missing values. (Хорошо! Теперь у нас есть набор данных без пропущенных значений.)
набор данных без пропущенных значений
Introduction
In real life situation, the available data is rarely clean. Each and every datasets can possibly have missing values, so the data cleaning is a major and most important part of every data science project.
In this article, we demonstrate some popular built-in Pandas tools for handling missing data in Python. This exercise is performed by using Kaggle’s House Prices dataset.
Why do we need to fill in the missing data?
Unfortunately, if we pass a missing value e.g not a number (NaN), most of the machine learning (ML) models that we want to use for the classification or regression problems will provide an error. Therefore, before starting towards any model building process, we need to prioritize the data cleaning process. The most elementary strategy is to remove all rows that contain missing values or, in extreme cases, entire columns that contain missing values. However, there is a disadvantage with this method as we will lose data which might affect our model performance. So, it’s not the best idea. Though, it can be useful when most values in a column are missing.
Loading and viewing the dataset:
The dataset used has 1460 observations with 79 explanatory feature variables describing every aspect of residential homes in different states of USA and one output variable to predict the final price of each home. The full details of these variables are described here. In this article, we will only focus on different methods to deal with the missing values.
Let’s start with importing Pandas and NumPy into our python environment and loading a .csv dataset into a pandas dataframe named df. Each and every examples shown in this article are verified on a Jupyter notebook.
Before starting to analyze the data and draw any conclusions, it is necessary to understand the presence of missing values in any dataset. Missing values in a dataset can be represented by different conventions (?, NaN, $, NA,.…).
How to know whether the dataset has any missing values?
To check whether our dataset has any missing values or not, the simplest way is to use df.info() function. This function will provide us the column names with the number of non-null values in each column.
There is also another way of finding whether we have null values in the data is by using the df.isnull() function. df.isnull().sum() is used to summarize total number of missing values per column.
From the above output, we found 19 columns with the missing values. To make our life a little easier it is better to write a function for missing values that will give an output of total percentage of missing values along with a distribution of all the columns with missing values present in a dataset. we will be using matplotlib library to plot the columns with missing data.
There are multiple ways of handling missing data and this is different for different types of datasets. There is no universal way of dealing with the missing data. You need to explore different options and try to determine which method is best for your dataset.
Now, let’s discuss about the methods of handling missing data:
- Deleting the rows/columns with missing data
- Imputing Missing Values (Filling the missing data with a value)
Deleting the rows/columns with missing data
The first method is to remove all rows that contain missing values or, in extreme cases, entire columns that contain missing values. This can be performed by using df.dropna() function. axis=0 or axis=1 is used to delete rows/columns with NaN values.
In our dataset, we observe 4 columns have more than 1000 NaN values (>65%). So, it is better to drop these columns.
Imputing Missing Values
The next method is to replace the missing values with a certain value. There are many options to pick from when replacing a missing value:
- Replace method.
- Replacing NaNs with zero .
- Replacing NaNs using Mean/Median/Mode of the column.
- Replacing NaNs by sklearn’s SimpleImputer()
- Replacing NaNs with k Nearest Neighbors (kNN)
- Replacing NaNs with the value from the previous row or the next row (using ffill or bfill method).
- Replacing NaNs with interpolation method
- Replace method:
Sometimes we have missing values in the dataset in the form of __, NA, @, ? etc. The easiest way to check these missing values is by printing the unique values of a particular column.
In this situation, we will replace all the missing values with NaN by using df.replace() function. Here, we specify both the value to be replaced and the replacement value. Now, it will be easier for us to deal with the null values rather than any undefined symbols.
2. Replacing NaNs with zero:
We will use Pandas df.fillna() function to replace missing values in a column with 0.
The same output can also be achieved by replace method.
3. Replacing NaNs with Mean/Median:
In case of a numerical column or variable (dtype : int, float), we can fill the missing values with their mean or median. If you have the dtype as object for a numeric column, pandas to_numeric() function is useful to convert the object type columns to the numeric ones.
It is best to replace the missing data with it’s median value only when the data has more outliers.
4. Replacing NaNs with Mode:
In case of a categorical column or variable (dtype : object), we can replace the missing data with the most common value called mode.
5. Imputing with SimpleImputer():
The sklearn library provides a function SimpleImputer() that can be used to replace missing values. This allows us to specify the value to replace by passing a startegy argument such as mean, median, mode or any constant.
In the above example, I have created a new dataframe df1 by selecting one column(MasVnrArea) from the existing dataframe df. This column has total 8 NaN values. All the missing values are imputed with the mean value by using SimpleImputer(strategy = ‘mean’).
Note: Mean/Median methods gives poor results on encoded categorical variables. Also, these methods (Mean,Median,Mode) also do not factor the correlations between different variables.
6. Imputing with k Nearest Neighbors:
The sklearn library provides a function KNNImputer() to replace missing values. This allows us to specify the value to replace the missing values with the mean value from nearest neighbors (n_neighbors) of the data point.
In the above example, I have created a new dataframe df2 by selecting two columns (MasVnrArea, SalePrice) from the existing dataframe df. The new dataframe has total 8 NaN values in MasVnrArea variable. All the missing values are imputed with the mean distance value of 3 nearest neigbors by using KNN.
7. Replacing NaNs with ffill/bfill method:
In this method, we can specify a forward-fill (ffill) to propagate the previous value in a forward direction or a back-fill (bfill) to propagate the value in a backward directon.
If a previous value is not available during a forward fill, the NaN value remains the same and vice-versa. So, you can choose ffill or bfill method for a column accordingly based on your dataset.
8. Replacing NaNs with interpolation method:
Another way to fill NaN values is by using interpolation techniques which can be performed by using interpolate() function. This method is very useful in time series data.
Conclusions
- We learnt that each and every datasets can possibly have missing values, so the data cleaning is a major and most important part of every data science project.
- There are different ways of filling missing values depending on a dataset. There is no rules of filling the missing values. You need to experiment and check which method works the best for your analysis.
- I would recommend going through this course by DataCamp for a detailed understanding.
This brings us to the end of this article. Thank you for going through this article. Hope now you understand better about how to deal with missing values. If you have any queries, feel free to message in the comment section.
Appropriate references are provided throughout the article. Some more useful article references and online course details are mentioned below.