{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Pandas support\n", "\n", "
\n", "\n", "**Warning:** pandas support is currently experimental, don't expect everything to work.\n", "\n", "
\n", "\n", "It is convenient to use the Pandas package when dealing with numerical data, so Pint provides PintArray. A PintArray is a Pandas Extension Array, which allows Pandas to recognise the Quantity and store it in Pandas DataFrames and Series." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Installation\n", "\n", "\n", "Pandas support is provided by `pint-pandas`. It is not available on PyPI yet, to install it use\n", "```\n", "python -m pip install git+https://github.com/hgrecco/pint-pandas.git\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This example will show the simplist way to use pandas with pint and the underlying objects. It's slightly fiddly as you are not reading from a file. A more normal use case is given in Reading a csv.\n", "\n", "First some imports (you don't need to import `pintpandas` for this to work)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd \n", "import pint" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, we create a DataFrame with PintArrays as columns." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = pd.DataFrame({\n", " \"torque\": pd.Series([1, 2, 2, 3], dtype=\"pint[lbf ft]\"),\n", " \"angular_velocity\": pd.Series([1, 2, 2, 3], dtype=\"pint[rpm]\"),\n", "})\n", "df" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Operations with columns are units aware so behave as we would intuitively expect." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df['power'] = df['torque'] * df['angular_velocity']\n", "df" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see the columns' units in the dtypes attribute" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.dtypes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each column can be accessed as a Pandas Series" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.power" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Which contains a PintArray" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.power.values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The PintArray contains a Quantity" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.power.values.quantity" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Pandas Series accessors are provided for most Quantity properties and methods, which will convert the result to a Series where possible." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.power.pint.units" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.power.pint.to(\"kW\").values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reading from csv\n", "\n", "Reading from files is the far more standard way to use pandas. To facilitate this, DataFrame accessors are provided to make it easy to get to PintArrays. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd \n", "import pint\n", "import pintpandas\n", "import io" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's the contents of the csv file." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "test_data = '''speed,mech power,torque,rail pressure,fuel flow rate,fluid power\n", "rpm,kW,N m,bar,l/min,kW\n", "1000.0,,10.0,1000.0,10.0,\n", "1100.0,,10.0,100000000.0,10.0,\n", "1200.0,,10.0,1000.0,10.0,\n", "1200.0,,10.0,1000.0,10.0,'''" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's read that into a DataFrame.\n", "Here io.StringIO is used in place of reading a file from disk, whereas a csv file path would typically be used and is shown commented." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = pd.read_csv(io.StringIO(test_data), header=[0, 1])\n", "# df = pd.read_csv(\"/path/to/test_data.csv\", header=[0, 1])\n", "df" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then use the DataFrame's pint accessor's quantify method to convert the columns from `np.ndarray`s to PintArrays, with units from the bottom column level." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.dtypes" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_ = df.pint.quantify(level=-1)\n", "df_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As previously, operations between DataFrame columns are unit aware" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_.speed * df_.torque" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_['mech power'] = df_.speed * df_.torque\n", "df_['fluid power'] = df_['fuel flow rate'] * df_['rail pressure']\n", "df_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The DataFrame's `pint.dequantify` method then allows us to retrieve the units information as a header row once again." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_.pint.dequantify()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This allows for some rather powerful abilities. For example, to change single column units" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_['fluid power'] = df_['fluid power'].pint.to(\"kW\")\n", "df_['mech power'] = df_['mech power'].pint.to(\"kW\")\n", "df_.pint.dequantify()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The units are harder to read than they need be, so lets change pints default format for displaying units." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pintpandas.PintType.ureg.default_format = \"~P\"\n", "df_.pint.dequantify()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or the entire table's units" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_.pint.to_base_units().pint.dequantify()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Advanced example\n", "This example shows alternative ways to use pint with pandas and other features.\n", "\n", "Start with the same imports." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd \n", "import pint\n", "import pintpandas" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll be use a shorthand for PintArray" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "PA_ = pintpandas.PintArray" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And set up a unit registry and quantity shorthand." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ureg = pint.UnitRegistry()\n", "Q_ = ureg.Quantity" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Operations between PintArrays of different unit registry will not work. We can change the unit registry that will be used in creating new PintArrays to prevent this issue." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pintpandas.PintType.ureg = ureg" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These are the possible ways to create a PintArray.\n", "\n", "Note that pint[unit] must be used for the Series constuctor, whereas the PintArray constructor allows the unit string or object." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = pd.DataFrame({\n", " \"length\" : pd.Series([1,2], dtype=\"pint[m]\"),\n", " \"width\" : PA_([2,3], dtype=\"pint[m]\"),\n", " \"distance\" : PA_([2,3], dtype=\"m\"),\n", " \"height\" : PA_([2,3], dtype=ureg.m),\n", " \"depth\" : PA_.from_1darray_quantity(Q_([2,3],ureg.m)),\n", " })\n", "df" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.length.values.units" ] } ], "metadata": { "anaconda-cloud": {}, "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.6" } }, "nbformat": 4, "nbformat_minor": 2 }