{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# default_exp transforms.aggregate"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Aggregate\n",
    "> Aggregation of records."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hide\n",
    "from nbdev.showdoc import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#export\n",
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#export\n",
    "def simple_aggregate(data,\n",
    "                     drop_duplicates=True,\n",
    "                     by='AFFINITY',\n",
    "                     aggregation='mean',\n",
    "                     weights=None,\n",
    "                     half_life=None,\n",
    "                     ):\n",
    "  \n",
    "  if drop_duplicates:\n",
    "    data = data.drop_duplicates()\n",
    "  \n",
    "  if by in data.columns:\n",
    "\n",
    "    if weights:\n",
    "      data = data.replace({by:weights})\n",
    "\n",
    "    if half_life:\n",
    "      t_ref = pd.to_datetime(data['TIMESTAMP']).max()\n",
    "      data[by] = data.apply(lambda x: x[by] * np.power(0.5, (t_ref - pd.to_datetime(x['TIMESTAMP'])).days / half_life), axis=1)\n",
    "\n",
    "    data = data.groupby(['USERID', 'ITEMID']).agg({by: aggregation}).reset_index()\n",
    "\n",
    "  else:\n",
    "\n",
    "    data[by] = 1\n",
    "    data = data.groupby(['USERID', 'ITEMID']).agg({by: 'count'}).reset_index()\n",
    "\n",
    "  return data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Author: Sparsh A.\n",
      "\n",
      "Last updated: 2021-12-18 06:58:48\n",
      "\n",
      "Compiler    : GCC 7.5.0\n",
      "OS          : Linux\n",
      "Release     : 5.4.104+\n",
      "Machine     : x86_64\n",
      "Processor   : x86_64\n",
      "CPU cores   : 2\n",
      "Architecture: 64bit\n",
      "\n",
      "pandas : 1.1.5\n",
      "numpy  : 1.19.5\n",
      "IPython: 5.5.0\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#hide\n",
    "!pip install -q watermark\n",
    "%reload_ext watermark\n",
    "%watermark -a \"Sparsh A.\" -m -iv -u -t -d"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
