{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. Обзор библиотеки pandas, важность подготовки данных\n", "\n", "## 1.1. [Pandas](http://pandas.pydata.org/) - библиотека Python для анализа данных\n", "\n", "* Быстрая и эффективная работа с объектами таблиц (DataFrame) с индексацией; \n", "* **Чтение и запись данных между данными в памяти компьютера и файлами в разных форматах: CSV, текстовые файлы, Microsoft Excel, SQL-базы данных, HDF5;**\n", "* **Обработка пропущенных и неформатированных данных;**\n", "* Изменение формы, расположения, структуры данных;\n", "* Срезы на основе индексов и названий колонок, создание подмножеств для больших объёмов данных;\n", "\n", "Основными структурами данных в pandas являются классы *Series* и *DataFrame*.\n", "\n", "**Series** - это одномерный индексированный массив данных одного типа.\n", "\n", "**DataFrame** – двухмерная структура данных, таблица, каждый столбец которой содержит данные одного типа.\n", "\n", "Часто загружаемые с помощью pandas данные хранятся как таблицы. Популярные форматы таблиц:\n", " - .csv = Comma Separated Valuse, .tsv = Tab Separated Values,\n", " - Microsoft Excel: .xls, .xlsx,\n", " - HDF5,\n", " - базы данных SQL.\n", " \n", "Сегодня мы познакомимся с чтением данных из формата CSV, фильтрацией и базовой подготовкой данных для анализа." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1.2. Признаки (features) в анализе данных. Категориальные и числовые признаки\n", "\n", "Наиболее распространённая задача анализа данных - обучение с учителем. Имеется множество объектов и множество возможных ответов. Существует некоторая зависимость между ответами и объектами, но она неизвестна. Известна только конечная совокупность прецедентов — пар «объект, ответ», называемая обучающей выборкой. На основе этих данных требуется восстановить зависимость, то есть построить алгоритм, способный для любого объекта выдать достаточно точный ответ. (По материалу [machinelearning.ru](http://www.machinelearning.ru/wiki/index.php?title=%D0%9E%D0%B1%D1%83%D1%87%D0%B5%D0%BD%D0%B8%D0%B5_%D1%81_%D1%83%D1%87%D0%B8%D1%82%D0%B5%D0%BB%D0%B5%D0%BC).)\n", "\n", "Часто встречающимся типом входных данных является **признаковое описание** (матрица объекты-признаки). Каждый объект описывается набором своих характеристик, называемых признаками. Признаки могут быть числовыми или нечисловыми.\n", "\n", "**Числовые признаки** - характеристики данных, выраженные в числах: возраст, количество, размер детали, цена и т. д. Чаще всего такие признаки не требуют особой обработки.\n", "\n", "**Категориальные признаки** - определяют принадлежность к какой-то категории. Примеры: пол, город, время года, номер группы, категория товаров и т.п. Для автоматической обработки таких признаков вместо исходного значения значения категории (например, \"М\", \"Ж\" или \"Москва\", \"Лондон\") часто необходим перевод в числовую форму.\n", "\n", "Подробнее о кодировке категориальных признаков: \n", " https://habr.com/ru/company/ods/blog/326418/\n", " http://datareview.info/article/universalnyj-podxod-pochti-k-lyuboj-zadache-mashinnogo-obucheniya/\n", " \n", "Иногда выделяют **текстовые признаки**. Примеры: полное имя, комментарий, описание. Такие признаки могут оказаться незначимыми в задаче, тогда их можно исключить, иначе к ним тоже применяется обработка и кодировка." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Подготовка данных к анализу** включает в себя много этапов: очистка и исправление неверных данных, отбор и кодировка признаков, трансформация данных, удаление и создание новых признаков и т. д.\n", "\n", "Подробная классификация процедур подготовки данных: http://www.machinelearning.ru/wiki/images/9/91/PZAD2017_07_datapreprocessing.pdf" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
TitleYearGenresLanguageCountryContent RatingDurationAspect RatioBudgetGross Earnings...Facebook Likes - Actor 1Facebook Likes - Actor 2Facebook Likes - Actor 3Facebook Likes - cast TotalFacebook likes - MovieFacenumber in postersUser VotesReviews by UsersReviews by CrtiicsIMDB Score
0127 Hours2010Adventure|Biography|Drama|ThrillerEnglishUSAR94.01.8518000000.018329466.0...1100064222311984630000.0279179440.0450.07.6
13 Backyards2010DramaEnglishUSAR88.0NaN300000.0NaN...7956593011884920.055423.020.05.2
232010Comedy|Drama|RomanceGermanGermanyUnrated119.02.35NaN59774.0...242096920000.0421218.076.06.8
38: The Mormon Proposition2010DocumentaryEnglishUSAR80.01.782500000.099851.0...19112521000.0113830.028.07.1
4A Turtle's Tale: Sammy's Adventures2010Adventure|Animation|FamilyEnglishFrancePG88.02.35NaNNaN...783749602387402.0538522.056.06.1
\n", "

5 rows × 25 columns

\n", "
" ], "text/plain": [ " Title Year \\\n", "0 127 Hours  2010 \n", "1 3 Backyards  2010 \n", "2 3  2010 \n", "3 8: The Mormon Proposition  2010 \n", "4 A Turtle's Tale: Sammy's Adventures  2010 \n", "\n", " Genres Language Country Content Rating \\\n", "0 Adventure|Biography|Drama|Thriller English USA R \n", "1 Drama English USA R \n", "2 Comedy|Drama|Romance German Germany Unrated \n", "3 Documentary English USA R \n", "4 Adventure|Animation|Family English France PG \n", "\n", " Duration Aspect Ratio Budget Gross Earnings ... \\\n", "0 94.0 1.85 18000000.0 18329466.0 ... \n", "1 88.0 NaN 300000.0 NaN ... \n", "2 119.0 2.35 NaN 59774.0 ... \n", "3 80.0 1.78 2500000.0 99851.0 ... \n", "4 88.0 2.35 NaN NaN ... \n", "\n", " Facebook Likes - Actor 1 Facebook Likes - Actor 2 Facebook Likes - Actor 3 \\\n", "0 11000 642 223 \n", "1 795 659 301 \n", "2 24 20 9 \n", "3 191 12 5 \n", "4 783 749 602 \n", "\n", " Facebook Likes - cast Total Facebook likes - Movie Facenumber in posters \\\n", "0 11984 63000 0.0 \n", "1 1884 92 0.0 \n", "2 69 2000 0.0 \n", "3 210 0 0.0 \n", "4 3874 0 2.0 \n", "\n", " User Votes Reviews by Users Reviews by Crtiics IMDB Score \n", "0 279179 440.0 450.0 7.6 \n", "1 554 23.0 20.0 5.2 \n", "2 4212 18.0 76.0 6.8 \n", "3 1138 30.0 28.0 7.1 \n", "4 5385 22.0 56.0 6.1 \n", "\n", "[5 rows x 25 columns]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Loading (importing) pandas module with often used alias \"pd\"\n", "# Загрузка модуля pandas с коротким именем pd\n", "import pandas as pd\n", "\n", "# load Excel file with pandas as an example\n", "# Зазгрузка таблицы Excel \n", "excel_file = 'mov.xls'\n", "df = pd.read_excel(excel_file)\n", "\n", "# Review top rows of data\n", "# Просмотр верхней части таблицы\n", "df.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. Аккуратные данные (Tidy Data)\n", "\n", "## 2.1. Принципы аккуратных данных\n", "\n", "**“Data cleaning is one of the most frequent task in data science. No matter what kind of data you are dealing with or what kind of analysis you are performing, you will have to clean the data at some point.”** -- Jean-Nicholas Hould http://www.jeannicholashould.com/tidy-data-in-python.html\n", "\n", "\"**Аккуратные данные**\" - термин и набор правил для организации данных при статистических исследованиях из статьи Hadley Wickham, **[Tidy Data](http://www.jstatsoft.org/v59/i10)**, Vol. 59, Issue 10, Sep 2014, Journal of Statistical Software.\n", "\n", "* **Переменная (variable)** - оценка какого-то атрибута. Рост, вес, пол, день недели, размер... Переменная содержит все значения, которые отображают один и тот же атрибут всех объектов.\n", "* **Значение (value)**: конкретный результат измерения атрибута. 152 см, 80 кг, М/Ж, XXL. Каждое значение принадлежит переменной и наблюдению.\n", "* **Наблюдение (observation)** содержит все значения атрибутов, измеренные для одного и того же объекта (такого как человек, день, кинофильм).\n", "\n", "#### Три принципа аккуратных данных (Tidy Data) [http://vita.had.co.nz/papers/tidy-data.pdf]\n", "1. Каждая переменная формирует колонку и имеет значения\n", "2. Каждое наблюдение формирует строку (ряд)\n", "3. Каждый вид эксперимента формирует таблицу. То есть каждый факт выражается только в одном месте. Примеры: баллы студента по разным предметам и данные самого студента должны быть в разных таблицах, не должно быть дубликатов и разночтений.\n", "4. (При наличии многих таблиц, нужно включать колонки, которые связывают их https://en.wikipedia.org/wiki/Tidy_data)\n", "\n", "Иллюстрация принципов аккуратных данных из статьи https://r4ds.had.co.nz/tidy-data.html\n", "![Вид CSV файла](http://antakova.ru/wp-content/uploads/2019/01/tidy1.png \"Принципы аккуратных данных\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2.2. Распространённые проблемы неаккуратности данных\n", "\n", "Связанные с организацией данных в одной таблице:\n", "* Заголовки колонок - это значения, а не имена переменных\n", "* Несколько переменных хранятся в одной колонке\n", "* Переменные хранятся в колонках и строках\n", "\n", "Связанные с организацией группы таблиц:\n", "* Много типов наблюдений хранится в одной таблице\n", "* Один и тот же тип наблюдений хранится во многих таблицах\n", "\n", "Наш фокус в этом мастер-классе - организация данных в **_одной таблице_**.\n", "\n", "### Пример: заголовки колонок - это не имена переменных\n", "\n", "Из статьи [Tidy Data](http://vita.had.co.nz/papers/tidy-data.pdf)\n", "\n", "В этой таблице заголовок показывает доход в нескольких колонках.\n", "\n", "| religion | 10k-20k | 20k-30k |\n", "| -------------|:-------------:|----------:|\n", "| Agnostic | 27 | 34 |\n", "| Atheist | 12 | 25 |\n", "| Buddhist | 20 | 27 |\n", "\n", "Переменные в этом наборе - вид религии, доход (категориальный признак) и количество (или частота) людей такого дохода и религии. Для исправления этой таблицы по принципу аккуратных данных нужно из доход сделать переменной-колонкой, а её значения из бывших колонок сделать строками.\n", "\n", "| religion | income | frequency |\n", "| -------------|:-------------:|----------:|\n", "| Agnostic | 10k-20k | 27 |\n", "| Agnostic | 20k-30k | 34 |\n", "| Atheist | 10k-20k | 12 |\n", "| Atheist | 20k-30k | 25 |\n", "| Buddhist | 10k-20k | 20 |\n", "| Buddhist | 20k-30k | 27 |\n", "\n", "### Несколько переменных хранятся в одной колонке\n", "\n", "Источник примера - [tutorial](http://garrettgman.github.io/tidying/)\n", "\n", "Колонка \"ключ\" (key) меняет тип переменной, представленной в соседней колонке, и колонка \"значение\" value имеет либо количество случаев cases, либо общую численность населения в зависимости от ключа. Это небоходимо разделить по колонкам.\n", "\n", "| country | year | key | value |\n", "| -------------|:----------:|-----------:|-----------:|\n", "| Afghanistan | 1999 | cases | 745 |\n", "| Afghanistan | 1999 | population | 19987071 |\n", "| Afghanistan | 2000 | cases | 2666 |\n", "| Afghanistan | 2000 | population | 20595360 |\n", "| Brazil | 1999 | cases | 37737 |\n", "| Brazil | 1999 | population | 172006362 |\n", "| Brazil | 2000 | cases | 80488 |\n", "| Brazil | 2000 | population | 174504898 |\n", "\n", "В такой таблице неудобно считать средние, максимумы или минимумы по значениям cases, population.\n", "Аккуратное и более удобное расположение данных - создать колонки cases, population.\n", "\n", "| country | year | cases | population |\n", "| -------------|:----------:|-----------:|-----------:|\n", "| Afghanistan | 1999 | 745 | 19987071 |\n", "| Afghanistan | 2000 | 2666 | 20595360 |\n", "| Brazil | 1999 | 37737 | 172006362 |\n", "| Brazil | 2000 | 80488 | 174504898 |\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Переменные хранятся в колонках и строках\n", "\n", "**Пример 1.** Иллюстрация не полностью аккуратных данных из статьи http://garrettgman.github.io/tidying/\n", "![Переменные в колонках и строка](tidy7.png \"Не самые аккуратные данные\")\n", "\n", "**Пример 2.** По материалу https://habr.com/ru/post/248741/ \n", "\n", "Несколько студентов учились по разным предметам (classes) в течение семестра (term) и сдавали тесты в середине семестра (midterm) и в конце (final). Имеется таблица оценок студентов по всем тестам, которые они сдали. \n", "\n", "| name | test | class1 | class2 | class3 |\n", "| ----------|:------------:|-----------:|-------:|-------:|\n", "| Sally | midterm | A | NA | NA |\n", "| Sally | final | C | NA | NA |\n", "| Jeff | midterm | NA | D | A |\n", "| Jeff | final | NA | A | C |\n", "| Roger | midterm | NA | NA | A |\n", "| Roger | final | NA | NA | C |\n", "\n", "Столбцы class1, class2, class3 содержат значения одной переменной class. А значения столбца test (midterm, final) должны быть переменными и содержать результат теста для каждого студента.\n", "\n", "Создадим новую переменную class со значениями 1-3 и раскроем значения столбца test в переменные final-score и midterm-score.\n", "\n", "| name | class | final-score | midterm-score |\n", "| ----------|:------------:|------------:|--------------:|\n", "| Sally | 1 | C | A |\n", "| Jeff | 2 | A | D |\n", "| Jeff | 3 | C | A |\n", "| Roger | 3 | C | A |" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3. Загрузка файлов CSV через Excel и pandas\n", "\n", "## 3.1. Просмотр \"сырого\" файла CSV\n", "\n", "![Вид CSV файла](http://antakova.ru/wp-content/uploads/2019/01/csv.png \"CSV файл\")\n", "\n", "## 3.2. Удобный просмотр файла CSV с помощью Excel\n", "\n", "Метод получения Excel таблицы из CSV - это команда в меню **Data > Text to Columns**. В диалоге перевода данных в Excel много параметров (тип разделения, разделитель, что делать с дополнительными пробельными символами и т. д.). Результат - читаемая таблица.\n", "\n", "![Обработанный CSV в Excel](http://antakova.ru/wp-content/uploads/2019/01/excel.jpg \"Обработанный CSV в Excel\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 3.3. Загрузка CSV через методы pandas. Настройка параметров загрузки" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
This is a dataset of red wine quality with about 10 parameters
0fixed acidity;\"volatile acidity\";\"citric acid\"...
17.4;0.7;0;1.9;0.076;11;34;0.9978;3.51;0.56;9.4;5
27.8;0.88;0;2.6;0.098;25;67;0.9968;3.2;0.68;9.8;5
37.8;0.76;0.04;2.3;0.092;15;54;0.997;3.26;0.65;...
411.2;0.28;0.56;1.9;0.075;17;60;0.998;3.16;0.58...
\n", "
" ], "text/plain": [ " This is a dataset of red wine quality with about 10 parameters\n", "\n", "0 fixed acidity;\"volatile acidity\";\"citric acid\"... \n", "1 7.4;0.7;0;1.9;0.076;11;34;0.9978;3.51;0.56;9.4;5 \n", "2 7.8;0.88;0;2.6;0.098;25;67;0.9968;3.2;0.68;9.8;5 \n", "3 7.8;0.76;0.04;2.3;0.092;15;54;0.997;3.26;0.65;... \n", "4 11.2;0.28;0.56;1.9;0.075;17;60;0.998;3.16;0.58... " ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Read data from file 'winequality-red.csv' in the same directory that your python script\n", "# Простое чтение файла без параметров\n", "wine_filename = \"winequality-red.csv\"\n", "data = pd.read_csv(wine_filename) \n", "\n", "# Check top/head lines of loaded data, but the table seems strange\n", "# Убедимся, что данные присутствуют, однако таблица не выглядит верной\n", "data.head()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Unnamed: 0speedperiodwarningpair
0126111
1226111
2326111
3426111
4527111
\n", "
" ], "text/plain": [ " Unnamed: 0 speed period warning pair\n", "0 1 26 1 1 1\n", "1 2 26 1 1 1\n", "2 3 26 1 1 1\n", "3 4 26 1 1 1\n", "4 5 27 1 1 1" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Loading CSV file from WEB (URL)\n", "# Загрузка файла по WEB-адресу\n", "# May not work undef proxy\n", "url_csv = 'https://vincentarelbundock.github.io/Rdatasets/csv/boot/amis.csv'\n", "df2 = pd.read_csv(url_csv)\n", "\n", "df2.head()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function read_csv in module pandas.io.parsers:\n", "\n", "read_csv(filepath_or_buffer, sep=',', delimiter=None, header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression='infer', thousands=None, decimal=b'.', lineterminator=None, quotechar='\"', quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=None, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, doublequote=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None)\n", " Read CSV (comma-separated) file into DataFrame\n", " \n", " Also supports optionally iterating or breaking of the file\n", " into chunks.\n", " \n", " Additional help can be found in the `online docs for IO Tools\n", " `_.\n", " \n", " Parameters\n", " ----------\n", " filepath_or_buffer : str, pathlib.Path, py._path.local.LocalPath or any \\\n", " object with a read() method (such as a file handle or StringIO)\n", " The string could be a URL. Valid URL schemes include http, ftp, s3, and\n", " file. For file URLs, a host is expected. For instance, a local file could\n", " be file://localhost/path/to/table.csv\n", " sep : str, default ','\n", " Delimiter to use. If sep is None, the C engine cannot automatically detect\n", " the separator, but the Python parsing engine can, meaning the latter will\n", " be used and automatically detect the separator by Python's builtin sniffer\n", " tool, ``csv.Sniffer``. In addition, separators longer than 1 character and\n", " different from ``'\\s+'`` will be interpreted as regular expressions and\n", " will also force the use of the Python parsing engine. Note that regex\n", " delimiters are prone to ignoring quoted data. Regex example: ``'\\r\\t'``\n", " delimiter : str, default ``None``\n", " Alternative argument name for sep.\n", " delim_whitespace : boolean, default False\n", " Specifies whether or not whitespace (e.g. ``' '`` or ``'\\t'``) will be\n", " used as the sep. Equivalent to setting ``sep='\\s+'``. If this option\n", " is set to True, nothing should be passed in for the ``delimiter``\n", " parameter.\n", " \n", " .. versionadded:: 0.18.1 support for the Python parser.\n", " \n", " header : int or list of ints, default 'infer'\n", " Row number(s) to use as the column names, and the start of the\n", " data. Default behavior is to infer the column names: if no names\n", " are passed the behavior is identical to ``header=0`` and column\n", " names are inferred from the first line of the file, if column\n", " names are passed explicitly then the behavior is identical to\n", " ``header=None``. Explicitly pass ``header=0`` to be able to\n", " replace existing names. The header can be a list of integers that\n", " specify row locations for a multi-index on the columns\n", " e.g. [0,1,3]. Intervening rows that are not specified will be\n", " skipped (e.g. 2 in this example is skipped). Note that this\n", " parameter ignores commented lines and empty lines if\n", " ``skip_blank_lines=True``, so header=0 denotes the first line of\n", " data rather than the first line of the file.\n", " names : array-like, default None\n", " List of column names to use. If file contains no header row, then you\n", " should explicitly pass header=None. Duplicates in this list will cause\n", " a ``UserWarning`` to be issued.\n", " index_col : int or sequence or False, default None\n", " Column to use as the row labels of the DataFrame. If a sequence is given, a\n", " MultiIndex is used. If you have a malformed file with delimiters at the end\n", " of each line, you might consider index_col=False to force pandas to _not_\n", " use the first column as the index (row names)\n", " usecols : list-like or callable, default None\n", " Return a subset of the columns. If list-like, all elements must either\n", " be positional (i.e. integer indices into the document columns) or strings\n", " that correspond to column names provided either by the user in `names` or\n", " inferred from the document header row(s). For example, a valid list-like\n", " `usecols` parameter would be [0, 1, 2] or ['foo', 'bar', 'baz']. Element\n", " order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``.\n", " To instantiate a DataFrame from ``data`` with element order preserved use\n", " ``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns\n", " in ``['foo', 'bar']`` order or\n", " ``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]``\n", " for ``['bar', 'foo']`` order.\n", " \n", " If callable, the callable function will be evaluated against the column\n", " names, returning names where the callable function evaluates to True. An\n", " example of a valid callable argument would be ``lambda x: x.upper() in\n", " ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster\n", " parsing time and lower memory usage.\n", " squeeze : boolean, default False\n", " If the parsed data only contains one column then return a Series\n", " prefix : str, default None\n", " Prefix to add to column numbers when no header, e.g. 'X' for X0, X1, ...\n", " mangle_dupe_cols : boolean, default True\n", " Duplicate columns will be specified as 'X', 'X.1', ...'X.N', rather than\n", " 'X'...'X'. Passing in False will cause data to be overwritten if there\n", " are duplicate names in the columns.\n", " dtype : Type name or dict of column -> type, default None\n", " Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32}\n", " Use `str` or `object` together with suitable `na_values` settings\n", " to preserve and not interpret dtype.\n", " If converters are specified, they will be applied INSTEAD\n", " of dtype conversion.\n", " engine : {'c', 'python'}, optional\n", " Parser engine to use. The C engine is faster while the python engine is\n", " currently more feature-complete.\n", " converters : dict, default None\n", " Dict of functions for converting values in certain columns. Keys can either\n", " be integers or column labels\n", " true_values : list, default None\n", " Values to consider as True\n", " false_values : list, default None\n", " Values to consider as False\n", " skipinitialspace : boolean, default False\n", " Skip spaces after delimiter.\n", " skiprows : list-like or integer or callable, default None\n", " Line numbers to skip (0-indexed) or number of lines to skip (int)\n", " at the start of the file.\n", " \n", " If callable, the callable function will be evaluated against the row\n", " indices, returning True if the row should be skipped and False otherwise.\n", " An example of a valid callable argument would be ``lambda x: x in [0, 2]``.\n", " skipfooter : int, default 0\n", " Number of lines at bottom of file to skip (Unsupported with engine='c')\n", " nrows : int, default None\n", " Number of rows of file to read. Useful for reading pieces of large files\n", " na_values : scalar, str, list-like, or dict, default None\n", " Additional strings to recognize as NA/NaN. If dict passed, specific\n", " per-column NA values. By default the following values are interpreted as\n", " NaN: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan',\n", " '1.#IND', '1.#QNAN', 'N/A', 'NA', 'NULL', 'NaN', 'n/a', 'nan',\n", " 'null'.\n", " keep_default_na : bool, default True\n", " Whether or not to include the default NaN values when parsing the data.\n", " Depending on whether `na_values` is passed in, the behavior is as follows:\n", " \n", " * If `keep_default_na` is True, and `na_values` are specified, `na_values`\n", " is appended to the default NaN values used for parsing.\n", " * If `keep_default_na` is True, and `na_values` are not specified, only\n", " the default NaN values are used for parsing.\n", " * If `keep_default_na` is False, and `na_values` are specified, only\n", " the NaN values specified `na_values` are used for parsing.\n", " * If `keep_default_na` is False, and `na_values` are not specified, no\n", " strings will be parsed as NaN.\n", " \n", " Note that if `na_filter` is passed in as False, the `keep_default_na` and\n", " `na_values` parameters will be ignored.\n", " na_filter : boolean, default True\n", " Detect missing value markers (empty strings and the value of na_values). In\n", " data without any NAs, passing na_filter=False can improve the performance\n", " of reading a large file\n", " verbose : boolean, default False\n", " Indicate number of NA values placed in non-numeric columns\n", " skip_blank_lines : boolean, default True\n", " If True, skip over blank lines rather than interpreting as NaN values\n", " parse_dates : boolean or list of ints or names or list of lists or dict, default False\n", " \n", " * boolean. If True -> try parsing the index.\n", " * list of ints or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3\n", " each as a separate date column.\n", " * list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as\n", " a single date column.\n", " * dict, e.g. {'foo' : [1, 3]} -> parse columns 1, 3 as date and call result\n", " 'foo'\n", " \n", " If a column or index contains an unparseable date, the entire column or\n", " index will be returned unaltered as an object data type. For non-standard\n", " datetime parsing, use ``pd.to_datetime`` after ``pd.read_csv``\n", " \n", " Note: A fast-path exists for iso8601-formatted dates.\n", " infer_datetime_format : boolean, default False\n", " If True and `parse_dates` is enabled, pandas will attempt to infer the\n", " format of the datetime strings in the columns, and if it can be inferred,\n", " switch to a faster method of parsing them. In some cases this can increase\n", " the parsing speed by 5-10x.\n", " keep_date_col : boolean, default False\n", " If True and `parse_dates` specifies combining multiple columns then\n", " keep the original columns.\n", " date_parser : function, default None\n", " Function to use for converting a sequence of string columns to an array of\n", " datetime instances. The default uses ``dateutil.parser.parser`` to do the\n", " conversion. Pandas will try to call `date_parser` in three different ways,\n", " advancing to the next if an exception occurs: 1) Pass one or more arrays\n", " (as defined by `parse_dates`) as arguments; 2) concatenate (row-wise) the\n", " string values from the columns defined by `parse_dates` into a single array\n", " and pass that; and 3) call `date_parser` once for each row using one or\n", " more strings (corresponding to the columns defined by `parse_dates`) as\n", " arguments.\n", " dayfirst : boolean, default False\n", " DD/MM format dates, international and European format\n", " iterator : boolean, default False\n", " Return TextFileReader object for iteration or getting chunks with\n", " ``get_chunk()``.\n", " chunksize : int, default None\n", " Return TextFileReader object for iteration.\n", " See the `IO Tools docs\n", " `_\n", " for more information on ``iterator`` and ``chunksize``.\n", " compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'\n", " For on-the-fly decompression of on-disk data. If 'infer' and\n", " `filepath_or_buffer` is path-like, then detect compression from the\n", " following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no\n", " decompression). If using 'zip', the ZIP file must contain only one data\n", " file to be read in. Set to None for no decompression.\n", " \n", " .. versionadded:: 0.18.1 support for 'zip' and 'xz' compression.\n", " \n", " thousands : str, default None\n", " Thousands separator\n", " decimal : str, default '.'\n", " Character to recognize as decimal point (e.g. use ',' for European data).\n", " float_precision : string, default None\n", " Specifies which converter the C engine should use for floating-point\n", " values. The options are `None` for the ordinary converter,\n", " `high` for the high-precision converter, and `round_trip` for the\n", " round-trip converter.\n", " lineterminator : str (length 1), default None\n", " Character to break file into lines. Only valid with C parser.\n", " quotechar : str (length 1), optional\n", " The character used to denote the start and end of a quoted item. Quoted\n", " items can include the delimiter and it will be ignored.\n", " quoting : int or csv.QUOTE_* instance, default 0\n", " Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of\n", " QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).\n", " doublequote : boolean, default ``True``\n", " When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate\n", " whether or not to interpret two consecutive quotechar elements INSIDE a\n", " field as a single ``quotechar`` element.\n", " escapechar : str (length 1), default None\n", " One-character string used to escape delimiter when quoting is QUOTE_NONE.\n", " comment : str, default None\n", " Indicates remainder of line should not be parsed. If found at the beginning\n", " of a line, the line will be ignored altogether. This parameter must be a\n", " single character. Like empty lines (as long as ``skip_blank_lines=True``),\n", " fully commented lines are ignored by the parameter `header` but not by\n", " `skiprows`. For example, if ``comment='#'``, parsing\n", " ``#empty\\na,b,c\\n1,2,3`` with ``header=0`` will result in 'a,b,c' being\n", " treated as the header.\n", " encoding : str, default None\n", " Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python\n", " standard encodings\n", " `_\n", " dialect : str or csv.Dialect instance, default None\n", " If provided, this parameter will override values (default or not) for the\n", " following parameters: `delimiter`, `doublequote`, `escapechar`,\n", " `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to\n", " override values, a ParserWarning will be issued. See csv.Dialect\n", " documentation for more details.\n", " tupleize_cols : boolean, default False\n", " .. deprecated:: 0.21.0\n", " This argument will be removed and will always convert to MultiIndex\n", " \n", " Leave a list of tuples on columns as is (default is to convert to\n", " a MultiIndex on the columns)\n", " error_bad_lines : boolean, default True\n", " Lines with too many fields (e.g. a csv line with too many commas) will by\n", " default cause an exception to be raised, and no DataFrame will be returned.\n", " If False, then these \"bad lines\" will dropped from the DataFrame that is\n", " returned.\n", " warn_bad_lines : boolean, default True\n", " If error_bad_lines is False, and warn_bad_lines is True, a warning for each\n", " \"bad line\" will be output.\n", " low_memory : boolean, default True\n", " Internally process the file in chunks, resulting in lower memory use\n", " while parsing, but possibly mixed type inference. To ensure no mixed\n", " types either set False, or specify the type with the `dtype` parameter.\n", " Note that the entire file is read into a single DataFrame regardless,\n", " use the `chunksize` or `iterator` parameter to return the data in chunks.\n", " (Only valid with C parser)\n", " memory_map : boolean, default False\n", " If a filepath is provided for `filepath_or_buffer`, map the file object\n", " directly onto memory and access the data directly from there. Using this\n", " option can improve performance because there is no longer any I/O overhead.\n", " \n", " Returns\n", " -------\n", " result : DataFrame or TextParser\n", "\n" ] } ], "source": [ "help(pd.read_csv)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
This is a dataset of red wine quality with about 10 parameters
fixed acidityvolatile aciditycitric acidresidual sugarchloridesfree sulfur dioxidetotal sulfur dioxidedensitypHsulphatesalcoholquality
7.40.701.90.07611340.99783.510.569.45
7.80.8802.60.09825670.99683.20.689.85
0.760.042.30.09215540.9973.260.659.85
11.20.280.561.90.07517600.9983.160.589.86
\n", "
" ], "text/plain": [ " This is a dataset of red wine quality with about 10 parameters\n", "\n", "fixed acidity volatile acidity citric acid residual sugar chlorides free sulfur dioxide total sulfur dioxide density pH sulphates alcohol quality \n", "7.4 0.7 0 1.9 0.076 11 34 0.9978 3.51 0.56 9.4 5 \n", "7.8 0.88 0 2.6 0.098 25 67 0.9968 3.2 0.68 9.8 5 \n", " 0.76 0.04 2.3 0.092 15 54 0.997 3.26 0.65 9.8 5 \n", "11.2 0.28 0.56 1.9 0.075 17 60 0.998 3.16 0.58 9.8 6 " ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Basic parameters for data loading from CSV\n", "# Простые параметры для настройки загрузки CSV\n", "\n", "# delimiter - разделитель значений в CSV-файле\n", "data = pd.read_csv(wine_filename, delimiter=';') \n", "data.head()" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
fixed acidityvolatile aciditycitric acidresidual sugarchloridesfree sulfur dioxidetotal sulfur dioxidedensitypHsulphatesalcoholquality
07.40.700.001.90.07611.034.00.99783.510.569.45
17.80.880.002.60.09825.067.00.99683.200.689.85
27.80.760.042.30.09215.054.00.99703.260.659.85
311.20.280.561.90.07517.060.00.99803.160.589.86
47.40.700.001.90.07611.034.00.99783.510.569.45
\n", "
" ], "text/plain": [ " fixed acidity volatile acidity citric acid residual sugar chlorides \\\n", "0 7.4 0.70 0.00 1.9 0.076 \n", "1 7.8 0.88 0.00 2.6 0.098 \n", "2 7.8 0.76 0.04 2.3 0.092 \n", "3 11.2 0.28 0.56 1.9 0.075 \n", "4 7.4 0.70 0.00 1.9 0.076 \n", "\n", " free sulfur dioxide total sulfur dioxide density pH sulphates \\\n", "0 11.0 34.0 0.9978 3.51 0.56 \n", "1 25.0 67.0 0.9968 3.20 0.68 \n", "2 15.0 54.0 0.9970 3.26 0.65 \n", "3 17.0 60.0 0.9980 3.16 0.58 \n", "4 11.0 34.0 0.9978 3.51 0.56 \n", "\n", " alcohol quality \n", "0 9.4 5 \n", "1 9.8 5 \n", "2 9.8 5 \n", "3 9.8 6 \n", "4 9.4 5 " ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Dataset has description in first row and one empty row, we skip them with skiprows parameter\n", "# Файл содержит краткое описание данных в первой строке и пустую строку, пропустим их с помощью параметра skiprows\n", "data = pd.read_csv(wine_filename, delimiter=';', skiprows = 2) \n", "data.head()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
residual sugardensityalcoholquality
01.90.99789.45
12.60.99689.85
22.30.99709.85
31.90.99809.86
41.90.99789.45
\n", "
" ], "text/plain": [ " residual sugar density alcohol quality\n", "0 1.9 0.9978 9.4 5\n", "1 2.6 0.9968 9.8 5\n", "2 2.3 0.9970 9.8 5\n", "3 1.9 0.9980 9.8 6\n", "4 1.9 0.9978 9.4 5" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Choose columns of interest with usecols parameter\n", "# Выбор отдельных колонок для анализа с помощью параметра usecols по списку названий или номеров\n", "# usecols = ['col_name1', 'col_name2'] or usecols=[1, 2, 5]\n", "data = pd.read_csv(wine_filename, delimiter=';',\n", " skiprows = 2, usecols = ['residual sugar', 'density', 'alcohol', 'quality']) \n", "data.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.5. Обзор данных: head(), tail(), shape, columns, info(), describe()" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "data.tail()\n", " residual sugar density alcohol quality\n", "1594 2.0 0.99490 10.5 5\n", "1595 2.2 0.99512 11.2 6\n", "1596 2.3 0.99574 11.0 6\n", "1597 2.0 0.99547 10.2 5\n", "1598 3.6 0.99549 11.0 6\n", "\n", "data.shape\n", "(1599, 4)\n", "\n", "data.columns\n", "Index(['residual sugar', 'density', 'alcohol', 'quality'], dtype='object')\n", "\n", "data.info()\n", "\n", "RangeIndex: 1599 entries, 0 to 1598\n", "Data columns (total 4 columns):\n", "residual sugar 1599 non-null float64\n", "density 1599 non-null float64\n", "alcohol 1599 non-null float64\n", "quality 1599 non-null int64\n", "dtypes: float64(3), int64(1)\n", "memory usage: 50.0 KB\n", "None\n" ] } ], "source": [ "# Check the end of data\n", "# Просмотр последних строк данных\n", "print(\"data.tail()\")\n", "print(data.tail())\n", "\n", "# Get dimensions of data table\n", "# Узнаем размеры таблицы данных\n", "print()\n", "print(\"data.shape\")\n", "print(data.shape)\n", "\n", "# Print list of columns in data\n", "# Распечатаем список колонок в таблице данных\n", "print()\n", "print(\"data.columns\")\n", "print(data.columns)\n", "\n", "# Print basic information about dataset\n", "# Узнаем описание таблицы данных\n", "print()\n", "print(\"data.info()\")\n", "print(data.info())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Метод describe() показывает основные статистические характеристики данных по каждому числовому признаку (типы int64 и float64): число непропущенных значений, среднее, стандартное отклонение, диапазон, медиану, 0.25 и 0.75 квартили." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
residual sugardensityalcoholquality
count1599.0000001599.0000001599.0000001599.000000
mean2.5388060.99674710.4229835.636023
std1.4099280.0018871.0656680.807569
min0.9000000.9900708.4000003.000000
25%1.9000000.9956009.5000005.000000
50%2.2000000.99675010.2000006.000000
75%2.6000000.99783511.1000006.000000
max15.5000001.00369014.9000008.000000
\n", "
" ], "text/plain": [ " residual sugar density alcohol quality\n", "count 1599.000000 1599.000000 1599.000000 1599.000000\n", "mean 2.538806 0.996747 10.422983 5.636023\n", "std 1.409928 0.001887 1.065668 0.807569\n", "min 0.900000 0.990070 8.400000 3.000000\n", "25% 1.900000 0.995600 9.500000 5.000000\n", "50% 2.200000 0.996750 10.200000 6.000000\n", "75% 2.600000 0.997835 11.100000 6.000000\n", "max 15.500000 1.003690 14.900000 8.000000" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 4. Поиск некорректных данных с pandas" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.1 Просмотр данных, чтение строк и столбцов c методами loc, iloc\n", "\n", "По материалу https://www.shanelynn.ie/select-pandas-dataframe-rows-and-columns-using-iloc-loc-and-ix/\n", "![Выбор данных с помощью loc, iloc](http://antakova.ru/wp-content/uploads/2019/01/pandas_selection.png \"Выбор данных с помощью loc, iloc\")" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "row3 type\n", "\n", "\n", "row3 contents:\n", "Title 8: The Mormon Proposition \n", "Year 2010\n", "Genres Documentary\n", "Language English\n", "Country USA\n", "Content Rating R\n", "Duration 80\n", "Aspect Ratio 1.78\n", "Budget 2.5e+06\n", "Gross Earnings 99851\n", "Director Reed Cowan\n", "Actor 1 Dustin Lance Black\n", "Actor 2 Emily Pearson\n", "Actor 3 Gavin Newsom\n", "Facebook Likes - Director 0\n", "Facebook Likes - Actor 1 191\n", "Facebook Likes - Actor 2 12\n", "Facebook Likes - Actor 3 5\n", "Facebook Likes - cast Total 210\n", "Facebook likes - Movie 0\n", "Facenumber in posters 0\n", "User Votes 1138\n", "Reviews by Users 30\n", "Reviews by Crtiics 28\n", "IMDB Score 7.1\n", "Name: 3, dtype: object\n", "\n", "\n", " Title Year\n", "1 3 Backyards  2010\n", "2 3  2010\n", "4 A Turtle's Tale: Sammy's Adventures  2010\n" ] } ], "source": [ "# Selection of data by row or col position (iloc)\n", "# Выбор данных по строке и колонке - по нумерованной позиции iloc\n", "\n", "# Print row 3\n", "# Вывод строки с индексом 3\n", "row3 = df.iloc[3]\n", "print(\"row3 type\")\n", "print(type(row3))\n", "print()\n", "print(\"row3 contents:\")\n", "print(row3)\n", "\n", "# Create sub-dataFrame with list of row indexes and a slice of columns\n", "# Создание подтаблицы по индексам колонок и строк\n", "print()\n", "sub_df1 = df.iloc[[1,2,4],0:2]\n", "print(type(sub_df1))\n", "print(sub_df1)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Language Country\n", "0 English USA\n", "1 English USA\n", "2 German Germany\n", "3 English USA\n", "4 English France\n", "\n", " Language Country Content Rating Duration Aspect Ratio Budget\n", "0 English USA R 94.0 1.85 18000000.0\n", "1 English USA R 88.0 NaN 300000.0\n", "2 German Germany Unrated 119.0 2.35 NaN\n" ] } ], "source": [ "# Selection of data by label with loc[rows, columns]\n", "# Выбор данных по названиям (label)\n", "\n", "# Example: all rows and 2 named columns\n", "# Пример: все строки (:) и две колонки списком имён\n", "sub_frame1 = df.loc[:, ['Language', 'Country']]\n", "print(sub_frame1.head())\n", "\n", "print()\n", "\n", "# In this data frame row index is just numbers, rows don't have names\n", "# Example: rows 0, 1, 2 and a range of columns\n", "sub_frame2 = df.loc[0:2, 'Language':'Budget']\n", "print(sub_frame2.head())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.2. Поиск пропущенных данных" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "В разных типах таблиц пропущенные данные могут выглядеть как:\n", "* *np.nan* - это специальное значение из библиотеки numpy (np),\n", "* пустые значения,\n", "* неподходящие значения: пробельные символы, мусор\n", "\n", "В библиотеке pandas почти все пропущенные данные по умолчанию выражаются как **np.nan** " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задание: с помощью методов loc, iloc и здравого смысла исправить рейтинг фильма со значением \"Unrated\"" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
TitleYearGenresLanguageCountryContent RatingDurationAspect RatioBudgetGross Earnings...Facebook Likes - Actor 1Facebook Likes - Actor 2Facebook Likes - Actor 3Facebook Likes - cast TotalFacebook likes - MovieFacenumber in postersUser VotesReviews by UsersReviews by CrtiicsIMDB Score
0127 Hours2010Adventure|Biography|Drama|ThrillerEnglishUSAR94.01.8518000000.018329466.0...1100064222311984630000.0279179440.0450.07.6
13 Backyards2010DramaEnglishUSAR88.0NaN300000.0NaN...7956593011884920.055423.020.05.2
232010Comedy|Drama|RomanceGermanGermanyUnrated119.02.35NaN59774.0...242096920000.0421218.076.06.8
38: The Mormon Proposition2010DocumentaryEnglishUSAR80.01.782500000.099851.0...19112521000.0113830.028.07.1
4A Turtle's Tale: Sammy's Adventures2010Adventure|Animation|FamilyEnglishFrancePG88.02.35NaNNaN...783749602387402.0538522.056.06.1
\n", "

5 rows × 25 columns

\n", "
" ], "text/plain": [ " Title Year \\\n", "0 127 Hours  2010 \n", "1 3 Backyards  2010 \n", "2 3  2010 \n", "3 8: The Mormon Proposition  2010 \n", "4 A Turtle's Tale: Sammy's Adventures  2010 \n", "\n", " Genres Language Country Content Rating \\\n", "0 Adventure|Biography|Drama|Thriller English USA R \n", "1 Drama English USA R \n", "2 Comedy|Drama|Romance German Germany Unrated \n", "3 Documentary English USA R \n", "4 Adventure|Animation|Family English France PG \n", "\n", " Duration Aspect Ratio Budget Gross Earnings ... \\\n", "0 94.0 1.85 18000000.0 18329466.0 ... \n", "1 88.0 NaN 300000.0 NaN ... \n", "2 119.0 2.35 NaN 59774.0 ... \n", "3 80.0 1.78 2500000.0 99851.0 ... \n", "4 88.0 2.35 NaN NaN ... \n", "\n", " Facebook Likes - Actor 1 Facebook Likes - Actor 2 Facebook Likes - Actor 3 \\\n", "0 11000 642 223 \n", "1 795 659 301 \n", "2 24 20 9 \n", "3 191 12 5 \n", "4 783 749 602 \n", "\n", " Facebook Likes - cast Total Facebook likes - Movie Facenumber in posters \\\n", "0 11984 63000 0.0 \n", "1 1884 92 0.0 \n", "2 69 2000 0.0 \n", "3 210 0 0.0 \n", "4 3874 0 2.0 \n", "\n", " User Votes Reviews by Users Reviews by Crtiics IMDB Score \n", "0 279179 440.0 450.0 7.6 \n", "1 554 23.0 20.0 5.2 \n", "2 4212 18.0 76.0 6.8 \n", "3 1138 30.0 28.0 7.1 \n", "4 5385 22.0 56.0 6.1 \n", "\n", "[5 rows x 25 columns]" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Example in our small dataset of movies\n", "# Пример в подтаблице фильмов рейтинг - не установлен и некоторые значения NaN.\n", "# Content Rating = Unrated и Aspect Ratio = NaN\n", "\n", "# How to fix \"Unrated\"\n", "# Content rating should be set up according to \n", "# https://en.wikipedia.org/wiki/Motion_Picture_Association_of_America_film_rating_system\n", "# Как исправить \"Unrated\" - специалист по данным должен принять решение.\n", "\n", "df.head()" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Language Country Content Rating Duration Aspect Ratio Budget\n", "0 False False False False False False\n", "1 False False False False True False\n", "2 False False False False False True\n", "\n", "Budget column in whole movies dataset has this count of NaN values:\n", "11\n" ] } ], "source": [ "na_mask = sub_frame2.isna()\n", "print(na_mask)\n", "print()\n", "\n", "# Example how to use: count NA values in one column\n", "# Пример: вычисление количества пропущенных значений в одной колонке для полной таблицы\n", "budget_col = df.loc[:, 'Budget']\n", "budget_col_na = budget_col.isna()\n", "\n", "print('Budget column in whole movies dataset has this count of NaN values:')\n", "print(budget_col_na.sum())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.3. Некорректные данные\n", "\n", "Данные могут присутствовать в таблице, но иметь проблемы: \n", "* неверный формат, \n", "* не подходить как категория признака, \n", "* иметь дубликаты,\n", "* содержать неточную информацию или ошибки\n", "* и другие :)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
TitleYearGenresLanguageCountryContent RatingDurationAspect RatioBudgetGross Earnings...Facebook Likes - Actor 1Facebook Likes - Actor 2Facebook Likes - Actor 3Facebook Likes - cast TotalFacebook likes - MovieFacenumber in postersUser VotesReviews by UsersReviews by CrtiicsIMDB Score
0127 Hours2010Adventure|Biography|Drama|ThrillerEnglishUSAR94.01.8518000000.018329466.0...1100064222311984630000.0279179440.0450.07.6
13 Backyards2010DramaEnglishUSAR88.0NaN300000.0NaN...7956593011884920.055423.020.05.2
232010Comedy|Drama|RomanceGermanGermanyUnrated119.02.35NaN59774.0...242096920000.0421218.076.06.8
38: The Mormon Proposition2010DocumentaryEnglishUSAR80.01.782500000.099851.0...19112521000.0113830.028.07.1
4A Turtle's Tale: Sammy's Adventures2010Adventure|Animation|FamilyEnglishFrancePG88.02.35NaNNaN...783749602387402.0538522.056.06.1
5Alice in Wonderland2010Adventure|Family|FantasyEnglishUSAPG108.01.85200000000.0334185206.0...40000250001100079957240000.0306320736.0451.06.5
6Alice in Wonderland2010Adventure|Family|FantasyEnglishUSAPG108.01.85200000000.0334185206.0...40000250001100079957240000.0306336736.0451.06.5
7All Good Things2010-2011Crime|Drama|Mystery|Romance|ThrillerEnglishUSAR101.01.85NaN578382.0...3300040009023951502.04124967.0140.06.3
8Alpha and Omega2010Adventure|Animation|Comedy|Family|RomanceEnglishusaPG90.01.8520000000.025077977.0...681611518248600.01098684.084.05.3
9Amigo2010Drama|WarEnglishusaR124.0NaN1700000.0183490.0...3887605940.04638.035.05.8
\n", "

10 rows × 25 columns

\n", "
" ], "text/plain": [ " Title Year \\\n", "0 127 Hours  2010 \n", "1 3 Backyards  2010 \n", "2 3  2010 \n", "3 8: The Mormon Proposition  2010 \n", "4 A Turtle's Tale: Sammy's Adventures  2010 \n", "5 Alice in Wonderland  2010 \n", "6 Alice in Wonderland  2010 \n", "7 All Good Things  2010-2011 \n", "8 Alpha and Omega  2010 \n", "9 Amigo  2010 \n", "\n", " Genres Language Country Content Rating \\\n", "0 Adventure|Biography|Drama|Thriller English USA R \n", "1 Drama English USA R \n", "2 Comedy|Drama|Romance German Germany Unrated \n", "3 Documentary English USA R \n", "4 Adventure|Animation|Family English France PG \n", "5 Adventure|Family|Fantasy English USA PG \n", "6 Adventure|Family|Fantasy English USA PG \n", "7 Crime|Drama|Mystery|Romance|Thriller English USA R \n", "8 Adventure|Animation|Comedy|Family|Romance English usa PG \n", "9 Drama|War English usa R \n", "\n", " Duration Aspect Ratio Budget Gross Earnings ... \\\n", "0 94.0 1.85 18000000.0 18329466.0 ... \n", "1 88.0 NaN 300000.0 NaN ... \n", "2 119.0 2.35 NaN 59774.0 ... \n", "3 80.0 1.78 2500000.0 99851.0 ... \n", "4 88.0 2.35 NaN NaN ... \n", "5 108.0 1.85 200000000.0 334185206.0 ... \n", "6 108.0 1.85 200000000.0 334185206.0 ... \n", "7 101.0 1.85 NaN 578382.0 ... \n", "8 90.0 1.85 20000000.0 25077977.0 ... \n", "9 124.0 NaN 1700000.0 183490.0 ... \n", "\n", " Facebook Likes - Actor 1 Facebook Likes - Actor 2 Facebook Likes - Actor 3 \\\n", "0 11000 642 223 \n", "1 795 659 301 \n", "2 24 20 9 \n", "3 191 12 5 \n", "4 783 749 602 \n", "5 40000 25000 11000 \n", "6 40000 25000 11000 \n", "7 33000 4000 902 \n", "8 681 611 518 \n", "9 38 8 7 \n", "\n", " Facebook Likes - cast Total Facebook likes - Movie Facenumber in posters \\\n", "0 11984 63000 0.0 \n", "1 1884 92 0.0 \n", "2 69 2000 0.0 \n", "3 210 0 0.0 \n", "4 3874 0 2.0 \n", "5 79957 24000 0.0 \n", "6 79957 24000 0.0 \n", "7 39515 0 2.0 \n", "8 2486 0 0.0 \n", "9 60 594 0.0 \n", "\n", " User Votes Reviews by Users Reviews by Crtiics IMDB Score \n", "0 279179 440.0 450.0 7.6 \n", "1 554 23.0 20.0 5.2 \n", "2 4212 18.0 76.0 6.8 \n", "3 1138 30.0 28.0 7.1 \n", "4 5385 22.0 56.0 6.1 \n", "5 306320 736.0 451.0 6.5 \n", "6 306336 736.0 451.0 6.5 \n", "7 41249 67.0 140.0 6.3 \n", "8 10986 84.0 84.0 5.3 \n", "9 463 8.0 35.0 5.8 \n", "\n", "[10 rows x 25 columns]" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 1 example on mov.xls: see rows 8, 9 column Country = \"usa\", not \"USA\"\n", "# 2 example on mov.xls: see row 7, column Year = 2010-2011 seems incorrect\n", "# 4 example on mov.xls: see rows 5 and 6, this is the same movie twice\n", "df.head(10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 5. Исправление некорректных данных\n", "\n", "## 5.1. Удаление или замена значениями данных N/A (NaN)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
TitleYearGenresLanguageCountryContent RatingDurationAspect RatioBudgetGross Earnings...Facebook Likes - Actor 1Facebook Likes - Actor 2Facebook Likes - Actor 3Facebook Likes - cast TotalFacebook likes - MovieFacenumber in postersUser VotesReviews by UsersReviews by CrtiicsIMDB Score
0127 Hours2010Adventure|Biography|Drama|ThrillerEnglishUSAR94.01.8518000000.018329466.0...1100064222311984630000.0279179440.0450.07.6
38: The Mormon Proposition2010DocumentaryEnglishUSAR80.01.782500000.099851.0...19112521000.0113830.028.07.1
5Alice in Wonderland2010Adventure|Family|FantasyEnglishUSAPG108.01.85200000000.0334185206.0...40000250001100079957240000.0306320736.0451.06.5
6Alice in Wonderland2010Adventure|Family|FantasyEnglishUSAPG108.01.85200000000.0334185206.0...40000250001100079957240000.0306336736.0451.06.5
8Alpha and Omega2010Adventure|Animation|Comedy|Family|RomanceEnglishusaPG90.01.8520000000.025077977.0...681611518248600.01098684.084.05.3
\n", "

5 rows × 25 columns

\n", "
" ], "text/plain": [ " Title Year \\\n", "0 127 Hours  2010 \n", "3 8: The Mormon Proposition  2010 \n", "5 Alice in Wonderland  2010 \n", "6 Alice in Wonderland  2010 \n", "8 Alpha and Omega  2010 \n", "\n", " Genres Language Country Content Rating \\\n", "0 Adventure|Biography|Drama|Thriller English USA R \n", "3 Documentary English USA R \n", "5 Adventure|Family|Fantasy English USA PG \n", "6 Adventure|Family|Fantasy English USA PG \n", "8 Adventure|Animation|Comedy|Family|Romance English usa PG \n", "\n", " Duration Aspect Ratio Budget Gross Earnings ... \\\n", "0 94.0 1.85 18000000.0 18329466.0 ... \n", "3 80.0 1.78 2500000.0 99851.0 ... \n", "5 108.0 1.85 200000000.0 334185206.0 ... \n", "6 108.0 1.85 200000000.0 334185206.0 ... \n", "8 90.0 1.85 20000000.0 25077977.0 ... \n", "\n", " Facebook Likes - Actor 1 Facebook Likes - Actor 2 Facebook Likes - Actor 3 \\\n", "0 11000 642 223 \n", "3 191 12 5 \n", "5 40000 25000 11000 \n", "6 40000 25000 11000 \n", "8 681 611 518 \n", "\n", " Facebook Likes - cast Total Facebook likes - Movie Facenumber in posters \\\n", "0 11984 63000 0.0 \n", "3 210 0 0.0 \n", "5 79957 24000 0.0 \n", "6 79957 24000 0.0 \n", "8 2486 0 0.0 \n", "\n", " User Votes Reviews by Users Reviews by Crtiics IMDB Score \n", "0 279179 440.0 450.0 7.6 \n", "3 1138 30.0 28.0 7.1 \n", "5 306320 736.0 451.0 6.5 \n", "6 306336 736.0 451.0 6.5 \n", "8 10986 84.0 84.0 5.3 \n", "\n", "[5 rows x 25 columns]" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# drop missing data\n", "# Удаление строк с отсутствующими данными\n", "df_without_na = df.dropna(how='any')\n", "df_without_na.head()" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
TitleYearGenresLanguageCountryContent RatingDurationAspect RatioBudgetGross Earnings...Facebook Likes - Actor 1Facebook Likes - Actor 2Facebook Likes - Actor 3Facebook Likes - cast TotalFacebook likes - MovieFacenumber in postersUser VotesReviews by UsersReviews by CrtiicsIMDB Score
0127 Hours2010Adventure|Biography|Drama|ThrillerEnglishUSAR94.01.8518000000.018329466.0...1100064222311984630000.0279179440.0450.07.6
13 Backyards2010DramaEnglishUSAR88.00.00300000.00.0...7956593011884920.055423.020.05.2
232010Comedy|Drama|RomanceGermanGermanyUnrated119.02.350.059774.0...242096920000.0421218.076.06.8
38: The Mormon Proposition2010DocumentaryEnglishUSAR80.01.782500000.099851.0...19112521000.0113830.028.07.1
4A Turtle's Tale: Sammy's Adventures2010Adventure|Animation|FamilyEnglishFrancePG88.02.350.00.0...783749602387402.0538522.056.06.1
\n", "

5 rows × 25 columns

\n", "
" ], "text/plain": [ " Title Year \\\n", "0 127 Hours  2010 \n", "1 3 Backyards  2010 \n", "2 3  2010 \n", "3 8: The Mormon Proposition  2010 \n", "4 A Turtle's Tale: Sammy's Adventures  2010 \n", "\n", " Genres Language Country Content Rating \\\n", "0 Adventure|Biography|Drama|Thriller English USA R \n", "1 Drama English USA R \n", "2 Comedy|Drama|Romance German Germany Unrated \n", "3 Documentary English USA R \n", "4 Adventure|Animation|Family English France PG \n", "\n", " Duration Aspect Ratio Budget Gross Earnings ... \\\n", "0 94.0 1.85 18000000.0 18329466.0 ... \n", "1 88.0 0.00 300000.0 0.0 ... \n", "2 119.0 2.35 0.0 59774.0 ... \n", "3 80.0 1.78 2500000.0 99851.0 ... \n", "4 88.0 2.35 0.0 0.0 ... \n", "\n", " Facebook Likes - Actor 1 Facebook Likes - Actor 2 Facebook Likes - Actor 3 \\\n", "0 11000 642 223 \n", "1 795 659 301 \n", "2 24 20 9 \n", "3 191 12 5 \n", "4 783 749 602 \n", "\n", " Facebook Likes - cast Total Facebook likes - Movie Facenumber in posters \\\n", "0 11984 63000 0.0 \n", "1 1884 92 0.0 \n", "2 69 2000 0.0 \n", "3 210 0 0.0 \n", "4 3874 0 2.0 \n", "\n", " User Votes Reviews by Users Reviews by Crtiics IMDB Score \n", "0 279179 440.0 450.0 7.6 \n", "1 554 23.0 20.0 5.2 \n", "2 4212 18.0 76.0 6.8 \n", "3 1138 30.0 28.0 7.1 \n", "4 5385 22.0 56.0 6.1 \n", "\n", "[5 rows x 25 columns]" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Simple fill missing data with 0 value\n", "# Простая замена отсутствующих данных нулями\n", "# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html\n", "df_filled = df.fillna(value=0)\n", "df_filled.head()" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "mean film budget is\n", "36309750.0\n", "\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
TitleYearGenresLanguageCountryContent RatingDurationAspect RatioBudgetGross Earnings...Facebook Likes - Actor 1Facebook Likes - Actor 2Facebook Likes - Actor 3Facebook Likes - cast TotalFacebook likes - MovieFacenumber in postersUser VotesReviews by UsersReviews by CrtiicsIMDB Score
0127 Hours2010Adventure|Biography|Drama|ThrillerEnglishUSAR94.01.8518000000.018329466.0...1100064222311984630000.0279179440.0450.07.6
13 Backyards2010DramaEnglishUSAR88.0NaN300000.0NaN...7956593011884920.055423.020.05.2
232010Comedy|Drama|RomanceGermanGermanyUnrated119.02.3536309750.059774.0...242096920000.0421218.076.06.8
38: The Mormon Proposition2010DocumentaryEnglishUSAR80.01.782500000.099851.0...19112521000.0113830.028.07.1
4A Turtle's Tale: Sammy's Adventures2010Adventure|Animation|FamilyEnglishFrancePG88.02.3536309750.0NaN...783749602387402.0538522.056.06.1
\n", "

5 rows × 25 columns

\n", "
" ], "text/plain": [ " Title Year \\\n", "0 127 Hours  2010 \n", "1 3 Backyards  2010 \n", "2 3  2010 \n", "3 8: The Mormon Proposition  2010 \n", "4 A Turtle's Tale: Sammy's Adventures  2010 \n", "\n", " Genres Language Country Content Rating \\\n", "0 Adventure|Biography|Drama|Thriller English USA R \n", "1 Drama English USA R \n", "2 Comedy|Drama|Romance German Germany Unrated \n", "3 Documentary English USA R \n", "4 Adventure|Animation|Family English France PG \n", "\n", " Duration Aspect Ratio Budget Gross Earnings ... \\\n", "0 94.0 1.85 18000000.0 18329466.0 ... \n", "1 88.0 NaN 300000.0 NaN ... \n", "2 119.0 2.35 36309750.0 59774.0 ... \n", "3 80.0 1.78 2500000.0 99851.0 ... \n", "4 88.0 2.35 36309750.0 NaN ... \n", "\n", " Facebook Likes - Actor 1 Facebook Likes - Actor 2 Facebook Likes - Actor 3 \\\n", "0 11000 642 223 \n", "1 795 659 301 \n", "2 24 20 9 \n", "3 191 12 5 \n", "4 783 749 602 \n", "\n", " Facebook Likes - cast Total Facebook likes - Movie Facenumber in posters \\\n", "0 11984 63000 0.0 \n", "1 1884 92 0.0 \n", "2 69 2000 0.0 \n", "3 210 0 0.0 \n", "4 3874 0 2.0 \n", "\n", " User Votes Reviews by Users Reviews by Crtiics IMDB Score \n", "0 279179 440.0 450.0 7.6 \n", "1 554 23.0 20.0 5.2 \n", "2 4212 18.0 76.0 6.8 \n", "3 1138 30.0 28.0 7.1 \n", "4 5385 22.0 56.0 6.1 \n", "\n", "[5 rows x 25 columns]" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# fill NA budget with some mean budget for these films\n", "# заполним пустой бюджет фильма средним значением по этой колонке\n", "mean = df['Budget'].mean()\n", "print('mean film budget is')\n", "print(mean)\n", "print()\n", "\n", "# inplace - значит заполнять в исходном датаFrame, а не только в возвращаемом новом\n", "df['Budget'].fillna(mean, inplace=True)\n", "\n", "df.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.2. Обработка строк для однотипного форматирования данных" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
TitleYearGenresLanguageCountryContent RatingDurationAspect RatioBudgetGross Earnings...Facebook Likes - Actor 1Facebook Likes - Actor 2Facebook Likes - Actor 3Facebook Likes - cast TotalFacebook likes - MovieFacenumber in postersUser VotesReviews by UsersReviews by CrtiicsIMDB Score
0127 Hours2010Adventure|Biography|Drama|ThrillerEnglishUSAR94.01,8518000000.018329466.0...1100064222311984630000.0279179440.0450.07,6
13 Backyards2010-2011DramaEnglishUSAR88.0NaN300000.0NaN...7956593011884920.055423.020.05,2
28: The Mormon Proposition2010DocumentaryEnglishUSAR80.01,782500000.099851.0...19112521000.0113830.028.07,1
3A Turtle's Tale: Sammy's Adventures2010Adventure|Animation|FamilyEnglishFrancePG88.02,35NaNNaN...783749602387402.0538522.056.06,1
4Alice in Wonderland2010Adventure|Family|FantasyEnglishUSAPG108.01,85200000000.0334185206.0...40000250001100079957240000.0306320736.0451.06,5
\n", "

5 rows × 25 columns

\n", "
" ], "text/plain": [ " Title Year \\\n", "0 127 Hours 2010 \n", "1 3 Backyards 2010-2011 \n", "2 8: The Mormon Proposition 2010 \n", "3 A Turtle's Tale: Sammy's Adventures 2010 \n", "4 Alice in Wonderland 2010 \n", "\n", " Genres Language Country Content Rating \\\n", "0 Adventure|Biography|Drama|Thriller English USA R \n", "1 Drama English USA R \n", "2 Documentary English USA R \n", "3 Adventure|Animation|Family English France PG \n", "4 Adventure|Family|Fantasy English USA PG \n", "\n", " Duration Aspect Ratio Budget Gross Earnings ... \\\n", "0 94.0 1,85 18000000.0 18329466.0 ... \n", "1 88.0 NaN 300000.0 NaN ... \n", "2 80.0 1,78 2500000.0 99851.0 ... \n", "3 88.0 2,35 NaN NaN ... \n", "4 108.0 1,85 200000000.0 334185206.0 ... \n", "\n", " Facebook Likes - Actor 1 Facebook Likes - Actor 2 Facebook Likes - Actor 3 \\\n", "0 11000 642 223 \n", "1 795 659 301 \n", "2 191 12 5 \n", "3 783 749 602 \n", "4 40000 25000 11000 \n", "\n", " Facebook Likes - cast Total Facebook likes - Movie Facenumber in posters \\\n", "0 11984 63000 0.0 \n", "1 1884 92 0.0 \n", "2 210 0 0.0 \n", "3 3874 0 2.0 \n", "4 79957 24000 0.0 \n", "\n", " User Votes Reviews by Users Reviews by Crtiics IMDB Score \n", "0 279179 440.0 450.0 7,6 \n", "1 554 23.0 20.0 5,2 \n", "2 1138 30.0 28.0 7,1 \n", "3 5385 22.0 56.0 6,1 \n", "4 306320 736.0 451.0 6,5 \n", "\n", "[5 rows x 25 columns]" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# load Excel file with pandas as an example\n", "# Зазгрузка таблицы Excel \n", "# Using encoding parameter because unicode defaiult encoder gives some errors on content\n", "file = 'mov.csv'\n", "df = pd.read_csv(file, encoding=\"ISO-8859-1\", delimiter=';');\n", "\n", "# Review top rows of data\n", "# Просмотр верхней части таблицы\n", "df.head()" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Title object\n", "Year object\n", "Genres object\n", "Language object\n", "Country object\n", "Content Rating object\n", "Duration float64\n", "Aspect Ratio object\n", "Budget float64\n", "Gross Earnings float64\n", "Director object\n", "Actor 1 object\n", "Actor 2 object\n", "Actor 3 object\n", "Facebook Likes - Director int64\n", "Facebook Likes - Actor 1 int64\n", "Facebook Likes - Actor 2 int64\n", "Facebook Likes - Actor 3 int64\n", "Facebook Likes - cast Total int64\n", "Facebook likes - Movie int64\n", "Facenumber in posters float64\n", "User Votes int64\n", "Reviews by Users float64\n", "Reviews by Crtiics float64\n", "IMDB Score object\n", "dtype: object" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Pay attention that dtype of \"Year\" is object, not a value\n", "# Because there are some years like 2010-2011\n", "df.dtypes" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0 2010\n", "1 2010-2011\n", "2 2010\n", "3 2010\n", "4 2010\n", "5 2010\n", "6 2010\n", "7 2010\n", "8 2010\n", "9 2010\n", "10 2010\n", "11 2010\n", "12 2010\n", "13 2009-2010\n", "14 2010\n", "15 2010\n", "16 2010\n", "17 2010\n", "18 2010\n", "19 2010\n", "20 2010\n", "21 2010\n", "22 2010\n", "23 2008 ?\n", "24 2010\n", "25 2010\n", "26 2010\n", "27 2010\n", "28 2010\n", "29 2010\n", "30 2010\n", "31 2010\n", "32 2010\n", "33 2010\n", "34 2010\n", "35 2010\n", "36 2010\n", "37 2010\n", "38 2010\n", "39 2010\n", "40 2010\n", "41 2010\n", "42 2010\n", "43 2010\n", "44 2010\n", "45 2010\n", "46 2010\n", "47 2010\n", "48 2010\n", "49 2010\n", "Name: Year, dtype: object" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.Year" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0 2010\n", "1 2010-2011\n", "2 2010\n", "3 2010\n", "4 2010\n", "5 2010\n", "6 2010\n", "7 2010\n", "8 2010\n", "9 2010\n", "10 2010\n", "11 2010\n", "12 2010\n", "13 2009-2010\n", "14 2010\n", "15 2010\n", "16 2010\n", "17 2010\n", "18 2010\n", "19 2010\n", "20 2010\n", "21 2010\n", "22 2010\n", "23 2008\n", "24 2010\n", "25 2010\n", "26 2010\n", "27 2010\n", "28 2010\n", "29 2010\n", "30 2010\n", "31 2010\n", "32 2010\n", "33 2010\n", "34 2010\n", "35 2010\n", "36 2010\n", "37 2010\n", "38 2010\n", "39 2010\n", "40 2010\n", "41 2010\n", "42 2010\n", "43 2010\n", "44 2010\n", "45 2010\n", "46 2010\n", "47 2010\n", "48 2010\n", "49 2010\n", "Name: Year, dtype: object" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Replace \" ?\" first and then choose the ending year\n", "df.Year = df.Year.replace(\"2008 ?\", \"2008\")\n", "\n", "df.Year" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0 2010\n", "1 2011\n", "2 2010\n", "3 2010\n", "4 2010\n", "5 2010\n", "6 2010\n", "7 2010\n", "8 2010\n", "9 2010\n", "10 2010\n", "11 2010\n", "12 2010\n", "13 2010\n", "14 2010\n", "15 2010\n", "16 2010\n", "17 2010\n", "18 2010\n", "19 2010\n", "20 2010\n", "21 2010\n", "22 2010\n", "23 2008\n", "24 2010\n", "25 2010\n", "26 2010\n", "27 2010\n", "28 2010\n", "29 2010\n", "30 2010\n", "31 2010\n", "32 2010\n", "33 2010\n", "34 2010\n", "35 2010\n", "36 2010\n", "37 2010\n", "38 2010\n", "39 2010\n", "40 2010\n", "41 2010\n", "42 2010\n", "43 2010\n", "44 2010\n", "45 2010\n", "46 2010\n", "47 2010\n", "48 2010\n", "49 2010\n", "Name: Year, dtype: object" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Choose the ending year as film year\n", "# Выберем год окончания как год фильма\n", "def getEndingYear(str):\n", " return str[-4:]\n", "\n", "df['Year'] = df['Year'].apply(getEndingYear)\n", "\n", "df.Year" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Title object\n", "Year int64\n", "Genres object\n", "Language object\n", "Country object\n", "Content Rating object\n", "Duration float64\n", "Aspect Ratio object\n", "Budget float64\n", "Gross Earnings float64\n", "Director object\n", "Actor 1 object\n", "Actor 2 object\n", "Actor 3 object\n", "Facebook Likes - Director int64\n", "Facebook Likes - Actor 1 int64\n", "Facebook Likes - Actor 2 int64\n", "Facebook Likes - Actor 3 int64\n", "Facebook Likes - cast Total int64\n", "Facebook likes - Movie int64\n", "Facenumber in posters float64\n", "User Votes int64\n", "Reviews by Users float64\n", "Reviews by Crtiics float64\n", "IMDB Score object\n", "dtype: object" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Now covert year to int type\n", "# Теперь колонка с годом преобразуется в число целого типа\n", "df['Year'] = pd.to_numeric(df['Year'])\n", "\n", "df.dtypes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.3. Упражнение: исправить проблемы данных в колонке 'Country'" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0 USA\n", "1 USA\n", "2 USA\n", "3 France\n", "4 USA\n", "5 USA\n", "6 USA\n", "7 usa\n", "8 usa\n", "9 usa\n", "10 Germany\n", "11 UK\n", "12 Canada\n", "13 USA\n", "14 USA\n", "15 Australia\n", "16 Canada\n", "17 Mexico\n", "18 USA\n", "19 USA\n", "20 USA\n", "21 UK\n", "22 Spain\n", "23 USA\n", "24 USA\n", "25 canada\n", "26 USA\n", "27 UK\n", "28 USA\n", "29 USA\n", "30 USA\n", "31 USA\n", "32 USA\n", "33 Official site\n", "34 USA\n", "35 USA\n", "36 USA\n", "37 USA\n", "38 USA\n", "39 USA\n", "40 USA\n", "41 USA\n", "42 USA\n", "43 USA\n", "44 USA\n", "45 USA\n", "46 Sweden\n", "47 USA\n", "48 UK\n", "49 USA\n", "Name: Country, dtype: object" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Hint 1: issues in this column: 'Official site' value, 'canada' and 'Canada', 'USA' and 'usa',\n", "# Совет: проблемы в этой колонке - строчные и прописные буквы, неверное название страны 'Official site'\n", "\n", "# We can use functions from pandas.str\n", "# Можно использовать функции pandas для строк\n", "# dataFrame.Column.str.lower()\n", "# Converts all characters to lowercase.\n", "# dataFrame.Column.str.upper()\n", "# Converts all characters to uppercase.\n", "\n", "# Look at column to see its data problems\n", "# Просмотр колонки для визуального определения проблем с данными\n", "df.Country" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Title Country Strong\n", "Year 2010\n", "Genres Drama|Music\n", "Language English\n", "Country Official site\n", "Content Rating PG-13\n", "Duration 117\n", "Aspect Ratio 2,35\n", "Budget 1.5e+07\n", "Gross Earnings 2.02189e+07\n", "Director Shana Feste\n", "Actor 1 Leighton Meester\n", "Actor 2 Cinda McCain\n", "Actor 3 Tim McGraw\n", "Facebook Likes - Director 19\n", "Facebook Likes - Actor 1 3000\n", "Facebook Likes - Actor 2 646\n", "Facebook Likes - Actor 3 461\n", "Facebook Likes - cast Total 4204\n", "Facebook likes - Movie 0\n", "Facenumber in posters 4\n", "User Votes 14814\n", "Reviews by Users 114\n", "Reviews by Crtiics 135\n", "IMDB Score 6,3\n", "Name: 33, dtype: object" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Hint 2\n", "# print what is in row 33 where Country == Official site\n", "# Распечатаем строку 33, чтобы понять, для какого фильма неверно указана страна\n", "# Hint 2 - find out the real country of issuing this film here: https://www.imdb.com/title/tt1555064/\n", "# Можно узнать, в какой стране выпущен этот фильм на сайте https://www.imdb.com/title/tt1555064/\n", "df.loc[33, :]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 6. Cтатьи для самостоятельного изучения\n", "\n", "### 6.1. Загрузка и обработка файлов CSV c Pandas \n", "\n", "* [Python Pandas read_csv – Load Data from CSV Files](https://www.shanelynn.ie/python-pandas-read_csv-load-data-from-csv-files/)\n", "* [Interactive online tutorial for reading CSV with pandas from DataCamp](https://www.datacamp.com/community/tutorials/pandas-read-csv)\n", "\n", "### 6.2. Подготовка данных с Pandas, работа с признаками, создание аккуратных данных\n", "\n", "* [Selecting Subsets of Data in Pandas: Part 1, by Ted Petrou](https://medium.com/dunder-data/selecting-subsets-of-data-in-pandas-6fcd0170be9c)\n", "* [Открытый курс машинного обучения. Тема 1. Первичный анализ данных с Pandas](https://habr.com/ru/company/ods/blog/322626/)\n", "* [Продвинутая подготовка данных. Открытый курс машинного обучения. Тема 6. Построение и отбор признаков](https://habr.com/ru/company/ods/blog/325422/)\n", "* [Подготовка данных к анализу на языке R. Data tidying: Подготовка наборов данных для анализа на конкретных примерах](https://habr.com/ru/post/248741/)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.1" } }, "nbformat": 4, "nbformat_minor": 2 }