{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "df = pd.DataFrame({\"A\": [\"female\", \"female\", \"female\", \"female\", \"female\",\n", " \"male\", \"male\", \"male\", \"male\"],\n", " \"B\": [\"CS\", \"CS\", \"CS\", \"DS\", \"DS\",\n", " \"CS\", \"CS\", \"DS\", \"DS\"],\n", " \"C\": [\"MS\", \"PhD\", \"PhD\", \"MS\",\n", " \"MS\", \"PhD\", \"MS\", \"MS\", \"PhD\"],\n", " \"D\": [1, 7, 2, 5, 3, 2, 5, 3, 7]})\n", "df" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# rows are indexed by \"index\"\n", "# columns are indexed by \"columns\"\n", "# entries are the \"sum\" of all D values\n", "table = df.pivot_table('D', index=['A', 'B'],\n", " columns='C', aggfunc='sum')\n", "table" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "table = df.pivot_table('D', index=['C', 'B'],\n", " columns='A', aggfunc='mean')\n", "table" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "table = df.pivot_table('D', index=['C', 'B'],\n", " columns='A', aggfunc='count')\n", "table" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "table = df.pivot_table('D', index=['A', 'B'],\n", " columns='C', aggfunc='sum', fill_value=0)\n", "table" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "table = df.pivot_table('D', index=['C', 'B'],\n", " columns='A', aggfunc='max')\n", "table" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }