{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "The idea here is\n", "* to split a column into two new columns with one column containing the positives and the other negatives.\n", "* use a default of 0 when the condition is not true (i.e. all negatives in the positive column and all positives in the negative column are set to 0" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " C\n", "0 0.496714\n", "1 -0.138264\n", "2 0.647689\n", "3 1.523030\n", "4 -0.234153\n", "5 -0.234137\n", "6 1.579213\n", "7 0.767435\n" ] } ], "source": [ "import numpy as np\n", "import pandas as pd\n", "\n", "np.random.seed(42)\n", "df = pd.DataFrame({'C' : np.random.randn(8)})\n", "print(df)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " C C_pos C_neg\n", "0 0.496714 0.496714 0.000000\n", "1 -0.138264 0.000000 -0.138264\n", "2 0.647689 0.647689 0.000000\n", "3 1.523030 1.523030 0.000000\n", "4 -0.234153 0.000000 -0.234153\n", "5 -0.234137 0.000000 -0.234137\n", "6 1.579213 1.579213 0.000000\n", "7 0.767435 0.767435 0.000000\n" ] } ], "source": [ "df['C_pos'] = df['C'].where(df['C']>0, other=0)\n", "df['C_neg'] = df['C'].where(df['C']<0, other=0)\n", "print(df)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sample use case: Split a market value column into longs and shorts.\n", "\n", "Ref:- \n", "* https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html\n", "* https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('1.0.3', '1.18.1')" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(pd.__version__, np.__version__)" ] } ], "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.8.2" } }, "nbformat": 4, "nbformat_minor": 2 }