{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "21cfc41f-637c-4154-b177-5c3bfad84a8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from mlxtend.preprocessing import TransactionEncoder\n",
    "\n",
    "df = pd.read_csv('D:/이강성/Retail_Transactions_Dataset.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "2b8c94c7-682f-43cd-88d1-dacea5ef4491",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from mlxtend.preprocessing import TransactionEncoder\n",
    "from ast import literal_eval\n",
    "\n",
    "# 데이터 타입이 문자열(str)인 경우에만 실제 리스트로 변환하는 함수\n",
    "def to_list(x):\n",
    "    if isinstance(x, str):\n",
    "        try:\n",
    "            return literal_eval(x)\n",
    "        except (ValueError, SyntaxError):\n",
    "            # 문자열이지만 리스트 형태가 아닌 예외 상황 처리\n",
    "            return [x]\n",
    "    elif isinstance(x, list):\n",
    "        return x\n",
    "    else:\n",
    "        # 그 외의 타입(예: NaN 등) 처리\n",
    "        return []\n",
    "\n",
    "# 1. Product 열의 데이터를 안전하게 리스트 형식으로 일괄 변환\n",
    "df1 = df[df['Store_Type'] == 'Warehouse Club']\n",
    "df1['Product_List'] = df1['Product'].apply(to_list)\n",
    "\n",
    "# 2. TransactionEncoder 객체 생성 및 변환\n",
    "te = TransactionEncoder()\n",
    "te_ary = te.fit(df1['Product_List']).transform(df1['Product_List'])\n",
    "\n",
    "# 3. 변환된 데이터를 1과 0 형식의 데이터프레임으로 변환\n",
    "df_encoded = pd.DataFrame(te_ary, columns=te.columns_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "9c91787a-2980-48ec-b680-e1cad02f96a2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Air Freshener</th>\n",
       "      <th>Apple</th>\n",
       "      <th>BBQ Sauce</th>\n",
       "      <th>Baby Wipes</th>\n",
       "      <th>Banana</th>\n",
       "      <th>Bath Towels</th>\n",
       "      <th>Beef</th>\n",
       "      <th>Bread</th>\n",
       "      <th>Broom</th>\n",
       "      <th>Butter</th>\n",
       "      <th>...</th>\n",
       "      <th>Tomatoes</th>\n",
       "      <th>Toothbrush</th>\n",
       "      <th>Toothpaste</th>\n",
       "      <th>Trash Bags</th>\n",
       "      <th>Trash Cans</th>\n",
       "      <th>Tuna</th>\n",
       "      <th>Vacuum Cleaner</th>\n",
       "      <th>Vinegar</th>\n",
       "      <th>Water</th>\n",
       "      <th>Yogurt</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>...</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>...</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>False</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>...</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>...</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>...</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>5 rows × 81 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   Air Freshener  Apple  BBQ Sauce  Baby Wipes  Banana  Bath Towels   Beef  \\\n",
       "0          False  False      False       False   False        False  False   \n",
       "1          False  False      False       False   False        False  False   \n",
       "2          False   True      False       False   False        False  False   \n",
       "3          False  False      False       False   False        False   True   \n",
       "4          False  False      False       False   False        False  False   \n",
       "\n",
       "   Bread  Broom  Butter  ...  Tomatoes  Toothbrush  Toothpaste  Trash Bags  \\\n",
       "0  False  False   False  ...     False       False       False       False   \n",
       "1  False  False   False  ...     False       False       False       False   \n",
       "2  False  False   False  ...     False       False       False        True   \n",
       "3  False  False   False  ...     False       False       False       False   \n",
       "4  False  False   False  ...     False       False       False       False   \n",
       "\n",
       "   Trash Cans   Tuna  Vacuum Cleaner  Vinegar  Water  Yogurt  \n",
       "0       False  False           False    False  False   False  \n",
       "1       False  False           False    False  False   False  \n",
       "2       False  False           False    False  False   False  \n",
       "3       False  False           False    False  False   False  \n",
       "4       False  False           False    False  False   False  \n",
       "\n",
       "[5 rows x 81 columns]"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_encoded.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "ccc4c504-0de7-4453-a922-959fa1151200",
   "metadata": {},
   "outputs": [],
   "source": [
    "from mlxtend.frequent_patterns import apriori, association_rules\n",
    "\n",
    "frequent_itemsets = apriori(df_encoded, min_support=0.002, use_colnames=True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "3a3ea342-a0bb-48b6-b312-e5e4a327c1b8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>support</th>\n",
       "      <th>itemsets</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.035702</td>\n",
       "      <td>frozenset({Air Freshener})</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.035918</td>\n",
       "      <td>frozenset({Apple})</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.036242</td>\n",
       "      <td>frozenset({BBQ Sauce})</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.036464</td>\n",
       "      <td>frozenset({Baby Wipes})</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.036602</td>\n",
       "      <td>frozenset({Banana})</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>156</th>\n",
       "      <td>0.002352</td>\n",
       "      <td>frozenset({Toothpaste, Tuna})</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>157</th>\n",
       "      <td>0.002262</td>\n",
       "      <td>frozenset({Toothpaste, Vacuum Cleaner})</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>158</th>\n",
       "      <td>0.002124</td>\n",
       "      <td>frozenset({Toothpaste, Vinegar})</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>159</th>\n",
       "      <td>0.002220</td>\n",
       "      <td>frozenset({Water, Toothpaste})</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>160</th>\n",
       "      <td>0.002238</td>\n",
       "      <td>frozenset({Toothpaste, Yogurt})</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>161 rows × 2 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "      support                                 itemsets\n",
       "0    0.035702               frozenset({Air Freshener})\n",
       "1    0.035918                       frozenset({Apple})\n",
       "2    0.036242                   frozenset({BBQ Sauce})\n",
       "3    0.036464                  frozenset({Baby Wipes})\n",
       "4    0.036602                      frozenset({Banana})\n",
       "..        ...                                      ...\n",
       "156  0.002352            frozenset({Toothpaste, Tuna})\n",
       "157  0.002262  frozenset({Toothpaste, Vacuum Cleaner})\n",
       "158  0.002124         frozenset({Toothpaste, Vinegar})\n",
       "159  0.002220           frozenset({Water, Toothpaste})\n",
       "160  0.002238          frozenset({Toothpaste, Yogurt})\n",
       "\n",
       "[161 rows x 2 columns]"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "frequent_itemsets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "538b2d8b-349b-4e73-b1c8-9d2f9c2403af",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                       antecedents              consequents   support  \\\n",
      "20          frozenset({Deodorant})  frozenset({Toothpaste})  0.002574   \n",
      "37            frozenset({Ketchup})  frozenset({Toothpaste})  0.002550   \n",
      "71           frozenset({Tomatoes})  frozenset({Toothpaste})  0.002550   \n",
      "21            frozenset({Diapers})  frozenset({Toothpaste})  0.002568   \n",
      "34               frozenset({Iron})  frozenset({Toothpaste})  0.002490   \n",
      "..                             ...                      ...       ...   \n",
      "38  frozenset({Laundry Detergent})  frozenset({Toothpaste})  0.002130   \n",
      "23           frozenset({Dishware})  frozenset({Toothpaste})  0.002112   \n",
      "77            frozenset({Vinegar})  frozenset({Toothpaste})  0.002124   \n",
      "53   frozenset({Plant Fertilizer})  frozenset({Toothpaste})  0.002094   \n",
      "5         frozenset({Bath Towels})  frozenset({Toothpaste})  0.002094   \n",
      "\n",
      "    confidence      lift  \n",
      "20    0.071074  0.993951  \n",
      "37    0.070493  0.985826  \n",
      "71    0.070190  0.981593  \n",
      "21    0.069958  0.978343  \n",
      "34    0.068788  0.961992  \n",
      "..         ...       ...  \n",
      "38    0.058833  0.822772  \n",
      "23    0.058794  0.822224  \n",
      "77    0.058745  0.821544  \n",
      "53    0.058725  0.821252  \n",
      "5     0.058312  0.815489  \n",
      "\n",
      "[80 rows x 5 columns]\n"
     ]
    }
   ],
   "source": [
    "rules = association_rules(frequent_itemsets, metric=\"confidence\", min_threshold=0.05)\n",
    "# 결과 확인을 위해 필요한 컬럼만 선택해서 출력\n",
    "print(rules[['antecedents', 'consequents', 'support', 'confidence', 'lift']]\n",
    "      .sort_values(by='confidence', ascending=False))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "0861bf21-5e3d-4d1b-81f2-4237d11156ab",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "166685"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(df1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6b3fa60f-d125-412e-9a76-f1ff0e343e39",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
