{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nfrom datetime import timedelta\nfrom ast import literal_eval\nimport random","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","papermill":{"duration":0.022094,"end_time":"2022-07-26T23:15:20.878087","exception":false,"start_time":"2022-07-26T23:15:20.855993","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-07-28T00:45:03.418250Z","iopub.execute_input":"2022-07-28T00:45:03.419538Z","iopub.status.idle":"2022-07-28T00:45:03.445183Z","shell.execute_reply.started":"2022-07-28T00:45:03.419424Z","shell.execute_reply":"2022-07-28T00:45:03.444153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the data\ndfp_train = pd.read_csv(\"/kaggle/input/what-card-should-i-select-next/train.csv\")\ndfp_test = pd.read_csv(\"/kaggle/input/what-card-should-i-select-next/test.csv\")\ndfp_cards = pd.read_csv(\"/kaggle/input/what-card-should-i-select-next/cards.csv\")","metadata":{"papermill":{"duration":3.17962,"end_time":"2022-07-26T23:15:24.061393","exception":false,"start_time":"2022-07-26T23:15:20.881773","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-07-28T00:45:03.450015Z","iopub.execute_input":"2022-07-28T00:45:03.451047Z","iopub.status.idle":"2022-07-28T00:45:07.949627Z","shell.execute_reply.started":"2022-07-28T00:45:03.451009Z","shell.execute_reply":"2022-07-28T00:45:07.948435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Processing\ndfp_train[\"update_date\"] = pd.to_datetime(dfp_train[\"update_date\"])\nprint(\"Count of rows (dfp_train):\", len(dfp_train))","metadata":{"papermill":{"duration":0.143718,"end_time":"2022-07-26T23:15:24.208599","exception":false,"start_time":"2022-07-26T23:15:24.064881","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-07-28T00:45:23.119483Z","iopub.execute_input":"2022-07-28T00:45:23.120189Z","iopub.status.idle":"2022-07-28T00:45:23.257186Z","shell.execute_reply.started":"2022-07-28T00:45:23.120149Z","shell.execute_reply":"2022-07-28T00:45:23.256068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Select the deck produced on the last 7 days\ndays = 7\ndfp_train_select = dfp_train[dfp_train[\"update_date\"] >= dfp_train[\"update_date\"].max() - timedelta(days = days)].copy()\ndfp_train_select[\"cards\"] = dfp_train_select[\"cards\"].apply(lambda cards: literal_eval(cards))\nprint(\"Count of rows (dfp_train_select):\", len(dfp_train_select))","metadata":{"papermill":{"duration":0.163126,"end_time":"2022-07-26T23:15:24.375423","exception":false,"start_time":"2022-07-26T23:15:24.212297","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-07-28T00:45:27.158362Z","iopub.execute_input":"2022-07-28T00:45:27.158720Z","iopub.status.idle":"2022-07-28T00:45:27.216377Z","shell.execute_reply.started":"2022-07-28T00:45:27.158691Z","shell.execute_reply":"2022-07-28T00:45:27.215545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Determine the distribution of card in hte train dataset\ndfp_train_select_exploded = dfp_train_select.explode('cards')\ndfp_train_select_exploded.rename(mapper={\"cards\" : \"card\"}, axis=1, inplace=True)\nprint(\"Count of rows (dfp_train_select_exploded):\", len(dfp_train_select_exploded))","metadata":{"papermill":{"duration":0.046541,"end_time":"2022-07-26T23:15:24.425623","exception":false,"start_time":"2022-07-26T23:15:24.379082","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-07-28T00:45:50.506194Z","iopub.execute_input":"2022-07-28T00:45:50.506591Z","iopub.status.idle":"2022-07-28T00:45:50.540365Z","shell.execute_reply.started":"2022-07-28T00:45:50.506559Z","shell.execute_reply":"2022-07-28T00:45:50.539156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# build the dictionnary of ranking based on hero and kind of decks\ndfp_agg = dfp_train_select_exploded.groupby([ 'hero', 'is_wild', 'is_standard', 'card']).size().to_frame().reset_index()\ndfp_agg.columns = ['hero', 'is_wild', 'is_standard', 'card', 'count']\n\ndfp_agg[\"hero-is_wild-is_standard\"] = dfp_agg.apply(lambda row: f\"{row['hero']}-{row['is_wild']}-{row['is_standard']}\", axis=1)\ndfp_agg[\"dict_card_count\"] = dfp_agg.apply(lambda row: {\"card\" : row['card'], \"count\" : row['count']}, axis=1)\n\ndfp_agg = dfp_agg.groupby([\"hero-is_wild-is_standard\"])['dict_card_count'].apply(list).to_frame()\ndfp_agg.reset_index(inplace=True)\n\ndef rank_card(dict_card_count):\n    return pd.DataFrame(dict_card_count).sort_values(\"count\", ascending=False)[\"card\"].tolist()\n\ndfp_agg[\"ranking\"] = dfp_agg['dict_card_count'].apply(lambda dict_card_count: rank_card(dict_card_count))\ndict_ranking = dfp_agg[[\"hero-is_wild-is_standard\", \"ranking\"]].set_index(\"hero-is_wild-is_standard\").to_dict(orient=\"index\")","metadata":{"papermill":{"duration":0.195604,"end_time":"2022-07-26T23:15:24.625009","exception":false,"start_time":"2022-07-26T23:15:24.429405","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-07-28T00:46:11.656358Z","iopub.execute_input":"2022-07-28T00:46:11.656747Z","iopub.status.idle":"2022-07-28T00:46:11.791603Z","shell.execute_reply.started":"2022-07-28T00:46:11.656716Z","shell.execute_reply":"2022-07-28T00:46:11.790066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ncardids = dfp_cards[\"id\"].tolist()\ndef build_recommendations(hero, is_wild, is_standard, cards, dict_ranking, k=3):\n    deck_incomplete = literal_eval(cards)\n    key_ranking = f\"{hero}-{is_wild}-{is_standard}\"\n    recommendations = []\n    if key_ranking in dict_ranking:\n        ranked_cards = dict_ranking[key_ranking][\"ranking\"]\n        for elt in ranked_cards:\n            if deck_incomplete.count(elt) < 2:\n                recommendations.append(elt)\n                \n            if len(recommendations) == k:\n                break\n    \n    if len(recommendations) < k:\n        recommendations.extend(random.choices(cardids, k=k-len(recommendations)))\n        \n    return \" \".join([str(elt) for elt in recommendations])\n\ndfp_test[\"recommendations\"] = dfp_test.apply(lambda row: build_recommendations(row[\"hero\"], row[\"is_wild\"], row[\"is_standard\"], row[\"cards_incomplete\"], dict_ranking, k=3), axis=1)","metadata":{"papermill":{"duration":0.357463,"end_time":"2022-07-26T23:15:24.986150","exception":false,"start_time":"2022-07-26T23:15:24.628687","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-07-28T00:46:15.205826Z","iopub.execute_input":"2022-07-28T00:46:15.206236Z","iopub.status.idle":"2022-07-28T00:46:15.390052Z","shell.execute_reply.started":"2022-07-28T00:46:15.206199Z","shell.execute_reply":"2022-07-28T00:46:15.388832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dfp_submission = dfp_test[[\"deckid\", \"recommendations\"]].copy()\ndfp_submission.to_csv(\"submission.csv\", index=None)","metadata":{"papermill":{"duration":0.03022,"end_time":"2022-07-26T23:15:25.020228","exception":false,"start_time":"2022-07-26T23:15:24.990008","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-07-28T00:46:17.435227Z","iopub.execute_input":"2022-07-28T00:46:17.435634Z","iopub.status.idle":"2022-07-28T00:46:17.450921Z","shell.execute_reply.started":"2022-07-28T00:46:17.435602Z","shell.execute_reply":"2022-07-28T00:46:17.449851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"papermill":{"duration":0.003628,"end_time":"2022-07-26T23:15:25.027703","exception":false,"start_time":"2022-07-26T23:15:25.024075","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]}]}