{"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":"# Importing libraries\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tqdm import tqdm\nimport os\nfrom collections import defaultdict\nfrom PIL import Image\n\npd.set_option('display.max_columns', None)\npd.set_option('display.width', 500)\npd.set_option('display.expand_frame_repr', False)\n\n\nimport warnings\nwarnings.simplefilter(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:28:46.201891Z","iopub.execute_input":"2023-09-30T14:28:46.202205Z","iopub.status.idle":"2023-09-30T14:28:47.739472Z","shell.execute_reply.started":"2023-09-30T14:28:46.202178Z","shell.execute_reply":"2023-09-30T14:28:47.738258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reading datasets\n\ndf_trs = pd.read_csv('/kaggle/input/h-and-m-personalized-fashion-recommendations/transactions_train.csv')\ndf_articles = pd.read_csv('/kaggle/input/h-and-m-personalized-fashion-recommendations/articles.csv')\ndf_cust = pd.read_csv('/kaggle/input/h-and-m-personalized-fashion-recommendations/customers.csv')","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:28:47.741546Z","iopub.execute_input":"2023-09-30T14:28:47.742000Z","iopub.status.idle":"2023-09-30T14:30:16.564359Z","shell.execute_reply.started":"2023-09-30T14:28:47.741964Z","shell.execute_reply":"2023-09-30T14:30:16.563423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reorganizing the datasets to include \"Women's Clothing.\"\n\ndf_articles = df_articles[df_articles['index_group_name'] == 'Ladieswear']\ndf_trs = df_trs[df_trs['article_id'].isin(df_articles['article_id'])]\ndf_cust = df_cust[df_cust['customer_id'].isin(df_trs['customer_id'])]","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:30:16.565544Z","iopub.execute_input":"2023-09-30T14:30:16.565852Z","iopub.status.idle":"2023-09-30T14:30:23.549729Z","shell.execute_reply.started":"2023-09-30T14:30:16.565825Z","shell.execute_reply":"2023-09-30T14:30:23.548533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# The total number of product types\n\ndf_articles['article_id'].nunique()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:30:23.552248Z","iopub.execute_input":"2023-09-30T14:30:23.552545Z","iopub.status.idle":"2023-09-30T14:30:23.564960Z","shell.execute_reply.started":"2023-09-30T14:30:23.552521Z","shell.execute_reply":"2023-09-30T14:30:23.563914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Counting the folders and files in the directory.\n\ntotal_folders = 0\ntotal_files = 0\n\nfolder_info = []\nimages_names = []\n\npath = \"../input/h-and-m-personalized-fashion-recommendations\"\n\nfor base, dirs, files in tqdm(os.walk(path)):\n    for directories in dirs:\n        folder_info.append((directories, \n                            len(os.listdir(os.path.join(base, directories)))))\n        total_folders = total_folders + 1\n    \n    for _files in files:\n        total_files = total_files + 1\n        if (len(_files.split(\".jpg\"))==2):\n            images_names.append(_files.split(\".jpg\")[0])","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:30:23.566030Z","iopub.execute_input":"2023-09-30T14:30:23.566464Z","iopub.status.idle":"2023-09-30T14:33:08.856250Z","shell.execute_reply.started":"2023-09-30T14:30:23.566415Z","shell.execute_reply":"2023-09-30T14:33:08.855054Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating a dataset using the 'image_names' list.\n\nimage_name_df = pd.DataFrame(images_names, columns = [\"image_name\"])\nimage_name_df[\"article_id\"] = image_name_df[\"image_name\"].apply(lambda x: int(x[1:]))\nimage_name_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:33:08.858240Z","iopub.execute_input":"2023-09-30T14:33:08.859414Z","iopub.status.idle":"2023-09-30T14:33:08.950445Z","shell.execute_reply.started":"2023-09-30T14:33:08.859362Z","shell.execute_reply":"2023-09-30T14:33:08.949372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Merging df_articles and image_article_df.\n\nimage_article_df = df_articles[[\"article_id\", \n                                \"product_code\", \n                                \"product_group_name\", \n                                \"product_type_name\"]].merge(image_name_df, \n                                                            on=[\"article_id\"], \n                                                            how=\"left\")\nimage_article_df.head()\nimage_article_df.shape","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:33:08.951540Z","iopub.execute_input":"2023-09-30T14:33:08.951843Z","iopub.status.idle":"2023-09-30T14:33:09.002528Z","shell.execute_reply.started":"2023-09-30T14:33:08.951818Z","shell.execute_reply":"2023-09-30T14:33:09.001816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# How many products don't have photos?\n\narticle_no_image_df = image_article_df.loc[image_article_df.image_name.isna()]\narticle_no_image_df.head()\narticle_no_image_df.shape","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:33:09.003771Z","iopub.execute_input":"2023-09-30T14:33:09.004296Z","iopub.status.idle":"2023-09-30T14:33:09.019052Z","shell.execute_reply.started":"2023-09-30T14:33:09.004267Z","shell.execute_reply":"2023-09-30T14:33:09.017701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# A pie chart based on the total sales quantities of product groups.\n\nmerged_df = df_trs.merge(df_articles, on='article_id')\n\ngroup_sales = merged_df.groupby('product_group_name')['price'].sum()\n\ntotal_sales = group_sales.sum()\n\ngroup_percentages = (group_sales / total_sales) * 100\n\nthreshold = 3 \nsmall_percentages = group_percentages[group_percentages < threshold]\ngroup_sales['Other'] = group_sales[small_percentages.index].sum()\ngroup_sales = group_sales.drop(small_percentages.index)\n\ncolor_palette = 'Set2'\ncolors = plt.get_cmap(color_palette)(range(len(group_sales)))\n\nplt.figure(figsize=(8, 8))\nplt.pie(group_sales, labels=group_sales.index, autopct='%1.1f%%', startangle=140, colors=colors, textprops={'fontsize': 12})\n\nplt.gca().add_artist(plt.Circle((0, 0), 0.70, fc='white'))\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:33:09.020747Z","iopub.execute_input":"2023-09-30T14:33:09.021210Z","iopub.status.idle":"2023-09-30T14:33:35.991342Z","shell.execute_reply.started":"2023-09-30T14:33:09.021150Z","shell.execute_reply":"2023-09-30T14:33:35.990151Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Sales quantities for different seasons.\n\ndf_trs['t_dat'] = pd.to_datetime(df_trs['t_dat'])\n\nseasons = [\n    (pd.Timestamp('2018-09-20'), pd.Timestamp('2019-03-20')),\n    (pd.Timestamp('2019-03-21'), pd.Timestamp('2019-09-20')),\n    (pd.Timestamp('2019-09-21'), pd.Timestamp('2020-03-20')),\n    (pd.Timestamp('2020-03-21'), pd.Timestamp('2020-09-20'))\n]\n\nsales_by_season = []\nfor start_date, end_date in seasons:\n    sales = df_trs[(df_trs['t_dat'] >= start_date) & (df_trs['t_dat'] <= end_date)]['price'].sum()\n    sales_by_season.append(sales)\n\nseason_labels = ['Sep 2018 - Mar 2019', 'Mar 2019 - Sep 2019', 'Sep 2019 - Mar 2020', 'Mar 2020 - Sep 2020']\nfor i, label in enumerate(season_labels):\n    print(f\"{label}: {sales_by_season[i]:,.2f}\")","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:33:35.994541Z","iopub.execute_input":"2023-09-30T14:33:35.994914Z","iopub.status.idle":"2023-09-30T14:33:40.834981Z","shell.execute_reply.started":"2023-09-30T14:33:35.994884Z","shell.execute_reply":"2023-09-30T14:33:40.833945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# The products with the highest sales in each season.\n\n\ndf_trs['t_dat'] = pd.to_datetime(df_trs['t_dat'])\n\nmerged_data = df_trs.merge(df_articles[['article_id', 'prod_name']], on='article_id', how='left')\n\ndate_ranges = [\n    (pd.to_datetime('2018-09-20'), pd.to_datetime('2019-03-20')),\n    (pd.to_datetime('2019-03-21'), pd.to_datetime('2019-09-20')),\n    (pd.to_datetime('2019-09-21'), pd.to_datetime('2020-03-20')),\n    (pd.to_datetime('2020-03-21'), pd.to_datetime('2020-09-20'))\n]\n\nfig, axs = plt.subplots(2, 2, figsize=(15, 10))\naxs = axs.flatten()\n\nfor i, (start_date, end_date) in enumerate(date_ranges):\n    selected_data = merged_data[(merged_data['t_dat'] >= start_date) & (merged_data['t_dat'] <= end_date)]\n    \n    top_products_range = selected_data.groupby('prod_name')['price'].sum().nlargest(5).reset_index()\n    \n    sns.barplot(data=top_products_range, x='prod_name', y='price', ax=axs[i])\n    axs[i].set_xticklabels(axs[i].get_xticklabels(), rotation=45, ha='right')\n    axs[i].set_xlabel('Product Name')\n    axs[i].set_ylabel('Total Sales Amount')\n    axs[i].set_title(f'{start_date.strftime(\"%d-%b-%Y\")} - {end_date.strftime(\"%d-%b-%Y\")}')\n    axs[i].set_ylim(0, 2500)\n    axs[i].legend().set_visible(False)\n\nplt.tight_layout()\nplt.subplots_adjust(hspace=0.8)\n\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:33:40.836356Z","iopub.execute_input":"2023-09-30T14:33:40.836908Z","iopub.status.idle":"2023-09-30T14:33:54.102932Z","shell.execute_reply.started":"2023-09-30T14:33:40.836880Z","shell.execute_reply":"2023-09-30T14:33:54.101922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Total sales quantities for different combinations of color and product groups.\n\n\ndf_trs['t_dat'] = pd.to_datetime(df_trs['t_dat'])\n\nmerged_data = df_trs.merge(df_articles[['article_id', 'prod_name', 'colour_group_name', 'product_group_name']], on='article_id', how='left')\n\ncolor_group_sales = merged_data.groupby(['colour_group_name', 'product_group_name'])['price'].sum().reset_index()\n\nselected_product_groups = ['Garment Full body', 'Garment Upper body', 'Garment Lower body']\ncolor_group_sales_selected = color_group_sales[color_group_sales['product_group_name'].isin(selected_product_groups)]\n\ntop_colors = color_group_sales_selected.groupby('product_group_name', group_keys=False).apply(lambda x: x.nlargest(5, 'price')).reset_index(drop=True)\n\nsns.set_palette('Set2')\n\nfig, axs = plt.subplots(1, len(selected_product_groups), figsize=(18, 6))\nfor i, (product_group, data) in enumerate(top_colors.groupby('product_group_name')):\n    sizes = data['price']\n    labels = data['colour_group_name']\n    axs[i].pie(sizes, labels=labels, autopct=lambda p: '{:.1f}%'.format(p), startangle=140, textprops={'fontsize': 14})\n    axs[i].set_title(product_group, fontsize=16, fontweight='bold')\n\nplt.tight_layout(rect=[0, 0.03, 1, 0.95])\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:33:54.104427Z","iopub.execute_input":"2023-09-30T14:33:54.104844Z","iopub.status.idle":"2023-09-30T14:34:05.492563Z","shell.execute_reply.started":"2023-09-30T14:33:54.104805Z","shell.execute_reply":"2023-09-30T14:34:05.491469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Sales quantity by season.\n\ndf_trs['t_dat'] = pd.to_datetime(df_trs['t_dat'])\n\nmonthly_sales_20_to_20 = df_trs[df_trs['t_dat'].dt.day == 20]\n\nmonthly_sales_grouped = monthly_sales_20_to_20.resample('M', on='t_dat')['price'].sum()\n\ndate_ranges = [\n    (pd.to_datetime('2018-09-20'), pd.to_datetime('2019-03-20')),\n    (pd.to_datetime('2019-03-21'), pd.to_datetime('2019-09-20')),\n    (pd.to_datetime('2019-09-21'), pd.to_datetime('2020-03-20')),\n    (pd.to_datetime('2020-03-21'), pd.to_datetime('2020-09-20'))\n]\n\nplt.figure(figsize=(10, 6))\n\nfor i, (start_date, end_date) in enumerate(date_ranges):\n    plt.axvspan(start_date, end_date, color='C{}'.format(i), alpha=0.2, label=f'{start_date.strftime(\"%b %d, %Y\")} - {end_date.strftime(\"%b %d, %Y\")}')\n    \nplt.plot(monthly_sales_grouped.index, monthly_sales_grouped, marker='o', color='blue', label='Sales Amount')\n\nplt.ylabel('Total Sales Amount')\nplt.xticks(rotation=45)\nplt.legend()\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:34:05.493990Z","iopub.execute_input":"2023-09-30T14:34:05.494373Z","iopub.status.idle":"2023-09-30T14:34:08.648789Z","shell.execute_reply.started":"2023-09-30T14:34:05.494337Z","shell.execute_reply":"2023-09-30T14:34:08.647973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Total sales quantity.\n\ntotal_sales = df_trs['price'].sum()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:34:08.650177Z","iopub.execute_input":"2023-09-30T14:34:08.650763Z","iopub.status.idle":"2023-09-30T14:34:08.692282Z","shell.execute_reply.started":"2023-09-30T14:34:08.650733Z","shell.execute_reply":"2023-09-30T14:34:08.691128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Total number of products sold.\n\ntotal_quantity_sold = len(df_trs)","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:34:08.693787Z","iopub.execute_input":"2023-09-30T14:34:08.694091Z","iopub.status.idle":"2023-09-30T14:34:08.699025Z","shell.execute_reply.started":"2023-09-30T14:34:08.694066Z","shell.execute_reply":"2023-09-30T14:34:08.697778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Customer percentages by age group.\n\nbins = [18, 30, 40, 50, 100]\nlabels = ['18-30', '31-40', '41-50', '51+']\n\ndf_cust['age_group'] = pd.cut(df_cust['age'], bins=bins, labels=labels, right=False)\n\ncustomers_by_age = df_cust['age_group'].value_counts()\ntoplam_musteriler = customers_by_age.sum()\n\nyuzde_by_age = (customers_by_age / toplam_musteriler) * 100\n\nplt.figure(figsize=(10, 6))\nsns.set_palette('Set2')\nax = sns.barplot(x=yuzde_by_age.index, y=yuzde_by_age.values)\n\nfor p in ax.patches:\n    ax.annotate(f'{p.get_height():.1f}%', (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points', fontsize=16, fontweight='bold')\n\nplt.xlabel('Yaş Grubu', fontsize=14)\nplt.ylabel('Müşteri Yüzdesi (%)', fontsize=14)\nplt.xticks(fontsize=12)\nplt.yticks(fontsize=12)\nplt.ylim(0, 60)\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:34:08.700149Z","iopub.execute_input":"2023-09-30T14:34:08.700426Z","iopub.status.idle":"2023-09-30T14:34:09.060957Z","shell.execute_reply.started":"2023-09-30T14:34:08.700402Z","shell.execute_reply":"2023-09-30T14:34:09.059853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# The most sold products by season\n\n\ndf_trs['t_dat'] = pd.to_datetime(df_trs['t_dat'])\n\nmerged_data = df_trs.merge(df_articles[['article_id', 'prod_name']], on='article_id', how='left')\n\ndate_ranges = [\n    (pd.to_datetime('2018-09-20'), pd.to_datetime('2019-03-20')),\n    (pd.to_datetime('2019-03-21'), pd.to_datetime('2019-09-20')),\n    (pd.to_datetime('2019-09-21'), pd.to_datetime('2020-03-20')),\n    (pd.to_datetime('2020-03-21'), pd.to_datetime('2020-09-20'))\n]\n\nsns.set_palette('Set2')\n\nfig, axs = plt.subplots(2, 2, figsize=(15, 10))\naxs = axs.flatten()\n\nfor i, (start_date, end_date) in enumerate(date_ranges):\n    selected_data = merged_data[(merged_data['t_dat'] >= start_date) & (merged_data['t_dat'] <= end_date)]\n    \n    top_products_range = selected_data.groupby('prod_name')['price'].sum().nlargest(5).reset_index()\n\n    sns.barplot(data=top_products_range, y='prod_name', x='price', ax=axs[i])\n    axs[i].set_xlabel('Total Sales Amount')\n    axs[i].set_title(f'{start_date.strftime(\"%d-%b-%Y\")} - {end_date.strftime(\"%d-%b-%Y\")}')\n    axs[i].set_xlim(0, 2500)\n    axs[i].set_ylabel('')\n    axs[i].legend().set_visible(False)\n\nplt.tight_layout()\nplt.subplots_adjust(hspace=0.4)\n\n# Show the plots\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:34:09.062420Z","iopub.execute_input":"2023-09-30T14:34:09.062857Z","iopub.status.idle":"2023-09-30T14:34:22.430626Z","shell.execute_reply.started":"2023-09-30T14:34:09.062816Z","shell.execute_reply":"2023-09-30T14:34:22.429419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Total number of customers.\n\ntotal_customers = df_trs['customer_id'].nunique()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:34:22.432398Z","iopub.execute_input":"2023-09-30T14:34:22.432846Z","iopub.status.idle":"2023-09-30T14:34:28.449672Z","shell.execute_reply.started":"2023-09-30T14:34:22.432795Z","shell.execute_reply":"2023-09-30T14:34:28.448745Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Customers who receive fashion news regularly or monthly.\n\nfashion_news_regularly_count = df_cust[df_cust['fashion_news_frequency'].isin(['Regularly', 'Monthly'])]['customer_id'].nunique()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:34:28.450787Z","iopub.execute_input":"2023-09-30T14:34:28.451083Z","iopub.status.idle":"2023-09-30T14:34:29.025068Z","shell.execute_reply.started":"2023-09-30T14:34:28.451058Z","shell.execute_reply":"2023-09-30T14:34:29.024048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Top 10 customers with the highest spending.\n\ncustomer_summary = df_trs.groupby('customer_id').agg({\n    'price': 'sum',\n    'article_id': 'count'\n}).reset_index()\n\ncustomer_summary = customer_summary.sort_values(by='price', ascending=False)\n\nprint(customer_summary[['customer_id', 'price', 'article_id']].head(10))\n","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:34:29.026705Z","iopub.execute_input":"2023-09-30T14:34:29.027124Z","iopub.status.idle":"2023-09-30T14:34:39.869563Z","shell.execute_reply.started":"2023-09-30T14:34:29.027085Z","shell.execute_reply":"2023-09-30T14:34:39.868454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Grouping products by product groups and consolidating different products within each group. \n\ngrouped_products = defaultdict(list)\n\nfor _, row in image_article_df.iterrows():\n    grouped_products[row['product_group_name']].append(row['article_id'])\n\nunique_grouped_products = {group: set(ids) for group, ids in grouped_products.items()}","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:34:39.871677Z","iopub.execute_input":"2023-09-30T14:34:39.872135Z","iopub.status.idle":"2023-09-30T14:34:41.623262Z","shell.execute_reply.started":"2023-09-30T14:34:39.872093Z","shell.execute_reply":"2023-09-30T14:34:41.622479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Finding the best-selling products by product group.\n\ndef plot_image_samples(image_article_df, product_group_name, cols=1, rows=-1):\n    image_path = \"../input/h-and-m-personalized-fashion-recommendations/images/\"\n    _df = image_article_df.loc[image_article_df.product_group_name==product_group_name]\n    article_ids = _df.article_id.values[0:cols*rows]\n    plt.figure(figsize=(2 + 3 * cols, 2 + 4 * rows))\n    for i in range(cols * rows):\n        article_id = (\"0\" + str(article_ids[i]))[-10:]\n        plt.subplot(rows, cols, i + 1)\n        plt.axis('off')\n        plt.title(f\"{product_group_name} {article_id[:3]}\\n{article_id}.jpg\")\n        image = Image.open(f\"{image_path}{article_id[:3]}/{article_id}.jpg\")\n        plt.imshow(image)\n\nplot_image_samples(image_article_df, \"Garment Lower body\", 1, 1)\nplot_image_samples(image_article_df, \"Garment Full body\", 1, 1)\nplot_image_samples(image_article_df, \"Accessories\", 1, 1)\nplot_image_samples(image_article_df, \"Swimwear\", 1, 1)\nplot_image_samples(image_article_df, \"Underwear\", 1, 1)","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:34:41.624555Z","iopub.execute_input":"2023-09-30T14:34:41.624917Z","iopub.status.idle":"2023-09-30T14:34:44.424262Z","shell.execute_reply.started":"2023-09-30T14:34:41.624887Z","shell.execute_reply":"2023-09-30T14:34:44.423196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Merging transactions that occurred on the same day, grouped by date and customer, \n# and calculating the total number of merged transactions.\n\n\ndf_trs['t_dat'] = pd.to_datetime(df_trs['t_dat'])\n\ndf_trs['article_id'] = df_trs['article_id'].astype(str)\n\ncombined_transactions = df_trs.groupby(['customer_id', df_trs['t_dat'].dt.date])['article_id'].apply(lambda x: ', '.join(x)).reset_index()\n\ntotal_combined_transaction_count = len(combined_transactions)\n\nprint(\"Total Combined Transaction Count:\", total_combined_transaction_count)","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:34:44.425590Z","iopub.execute_input":"2023-09-30T14:34:44.425891Z","iopub.status.idle":"2023-09-30T14:37:55.937070Z","shell.execute_reply.started":"2023-09-30T14:34:44.425866Z","shell.execute_reply":"2023-09-30T14:37:55.935952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Counting customers based on the total number of transactions and finding the customer with \n# the highest number of transactions.\n\ntransaction_counts = combined_transactions['customer_id'].value_counts()\n\nmax_transaction_customer = transaction_counts.idxmax()\nmax_transaction_count = transaction_counts.max()\n\nprint(f\"The customer with the highest number of transactions is {max_transaction_customer} \"\nf\"with a total transaction count of {max_transaction_count}.\")","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:37:55.938592Z","iopub.execute_input":"2023-09-30T14:37:55.939993Z","iopub.status.idle":"2023-09-30T14:37:58.115093Z","shell.execute_reply.started":"2023-09-30T14:37:55.939948Z","shell.execute_reply":"2023-09-30T14:37:58.114033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# The number of active club members.\n\nunique_active_members = df_cust[df_cust['club_member_status'] == 'ACTIVE']['customer_id'].nunique()\n\nprint(\"Number of unique customers with ACTIVE club member status:\", unique_active_members)","metadata":{"execution":{"iopub.status.busy":"2023-09-30T14:37:58.116286Z","iopub.execute_input":"2023-09-30T14:37:58.116796Z","iopub.status.idle":"2023-09-30T14:37:58.861385Z","shell.execute_reply.started":"2023-09-30T14:37:58.116767Z","shell.execute_reply":"2023-09-30T14:37:58.860322Z"},"trusted":true},"execution_count":null,"outputs":[]}]}