{ "cells": [ { "cell_type": "markdown", "metadata": { "heading_collapsed": true }, "source": [ "### Библиотеки / данные " ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "импортируем numpy и pandas" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "настройки pandas" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "pd.options.display.max_rows = 10" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "- считываем данные\n", "- используем столбец Symbol в качестве индекса \n", "- считываем только столбцы ['Symbol', 'Sector', 'Price', 'Book Value']" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "| Column Name | Description\n", "| ------------- |:-------------:|\n", "|Symbol|Сокращенное название организации|\n", "|Name|Полное название организации|\n", "|Sector|Сектор экономики|\n", "|Price|Стоимость акции|\n", "|Dividend Yield|Дивидендная доходность|\n", "|Price/Earnings|Цена / прибыль|\n", "|Earnings/Share|Прибыль на акцию|\n", "|Book Value|Балансовая стоимость компании|\n", "|52 week low|52-недельный минимум|\n", "|52 week high|52-недельный максимум|\n", "|Market Cap|Рыночная капитализация|\n", "|EBITDA|**E**arnings **b**efore **i**nterest, **t**axes, **d**epreciation and **a**mortization|\n", "|Price/Sales|Цена / объём продаж|\n", "|Price/Book|Цена / балансовая стоимость|\n", "|SEC Filings|Ссылка *sec.gov*|" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500 = pd.read_csv(\"../data/sp500.csv\",\n", " index_col='Symbol', \n", " usecols=['Symbol', 'Sector', 'Price', 'Book Value'])" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true }, "source": [ "### Мотивация" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "создаем DataFame для примера" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "np.random.seed(123)\n", "df = pd.DataFrame({'value':np.random.random(10000), 'key':range(100, 10100)})\n", "df.head()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "отбираем строку, в котором значение столбца key равно 10099" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df[df.key==10099]" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "измеряем время выполнения операции отбора" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "%timeit df[df.key==10099]" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "превращаем столбец key в index" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df_with_index = df.set_index(['key'])\n", "df_with_index.head()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "теперь можно найти это значение с помощью индекса" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df_with_index.loc[10099]" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "и теперь операция выполняется намного быстрее" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "%timeit df_with_index.loc[10099]" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "
Вывод: использование индекса повышает скорость доступа к данным более чем в n раз!" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true }, "source": [ "### Операции" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### сброс" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "исследуем несколько строк датафрейма data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500.head(3)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "сбрасываем индекс, помещая значения индекса в столбец" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "index_moved_to_col = sp500.reset_index()\n", "index_moved_to_col.head()" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### установка" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "а теперь делаем столбец Sector индексом" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "index_moved_to_col.set_index('Sector').head()" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### над множествами" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "Датафреймы для примера:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "data_rnd_part_1 = sp500.sample(100, random_state=333)\n", "data_rnd_part_2 = sp500.sample(100, random_state=777)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "data_rnd_part_1.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "data_rnd_part_2.head()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "объединение:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "ind_union = data_rnd_part_1.index | data_rnd_part_2.index\n", "ind_union" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "пересечение" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "ind_intersection = data_rnd_part_1.index & data_rnd_part_2.index\n", "len(ind_intersection)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "разность" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "ind_diff = data_rnd_part_1.index.difference(data_rnd_part_2.index)\n", "len(ind_diff)" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true }, "source": [ "### Иерархическая индексация" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "сначала помещаем символы в столбец" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "reindexed = sp500.reset_index()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "reindexed.head()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "а теперь индексируем датафрейм data по столбцам Sector и Symbol" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "multi_fi = reindexed.set_index(['Sector', 'Symbol'])\n", "multi_fi.head()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "наш индекс - это MultiIndex" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true, "scrolled": true }, "outputs": [], "source": [ "type(multi_fi.index)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "он имеет два уровня" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "len(multi_fi.index.levels)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "каждый уровень индекса - это индекс" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "multi_fi.index.levels[1]" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "изменение порядка уровней индекса:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "multi_fi.reorder_levels([1, 0], axis=0).head()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "получаем все акции, которые имеют значение Industrials
обратите внимание, что в результатах индекс уровня 0 не выводится " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "multi_fi.xs('Industrials').head()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "отбираем строки, в которых индекс уровня 1 (Symbol) имеет значение ALLE" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "multi_fi.xs('ALLE', level=1)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "скомбинируем уровни индексов" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "multi_fi.xs('Industrials').xs('UPS')" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "комбинируем уровни индексов, используя кортеж" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "multi_fi.xs(('Industrials', 'UPS'))" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true }, "source": [ "### [Типы](http://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#index-types)" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### Основной тип Index" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "покажем, что столбцы фактически являются индексом" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500.columns" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500.index" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### Int64Index и RangeIndex" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "Явно создаем Int64Index" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df_i64 = pd.DataFrame(np.arange(10, 20), index=np.arange(0, 10))\n", "df_i64.head()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "смотрим индекс" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df_i64.index" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "по умолчанию мы получаем RangeIndex" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df_range = pd.DataFrame(np.arange(10, 15))\n", "df_range.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df_range.index" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### Float64Index" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "индексы, использующие Float64Index" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df_f64 = pd.DataFrame(np.arange(0, 1000, 5), \n", " np.arange(0.0, 100.0, 0.5))\n", "df_f64.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df_f64.index" ] } ], "metadata": { "hide_input": false, "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.0" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "247.391px" }, "toc_section_display": true, "toc_window_display": true } }, "nbformat": 4, "nbformat_minor": 2 }