SianK commited on
Commit
9263fb2
·
verified ·
1 Parent(s): a432c38

Upload 2 files

Browse files
Sian_Khoury_Hand_On_activity_4_Part_1.ipynb ADDED
@@ -0,0 +1,1252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "4ba6aba8"
7
+ },
8
+ "source": [
9
+ "# 🤖 **Data Collection, Creation, Storage, and Processing**\n"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {
15
+ "id": "jpASMyIQMaAq"
16
+ },
17
+ "source": [
18
+ "## **1.** 📦 Install required packages"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": 1,
24
+ "metadata": {
25
+ "colab": {
26
+ "base_uri": "https://localhost:8080/"
27
+ },
28
+ "id": "f48c8f8c",
29
+ "outputId": "4d0d052d-dec9-41c3-884d-dd95526f964a"
30
+ },
31
+ "outputs": [
32
+ {
33
+ "output_type": "stream",
34
+ "name": "stdout",
35
+ "text": [
36
+ "Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.12/dist-packages (4.13.5)\n",
37
+ "Requirement already satisfied: pandas in /usr/local/lib/python3.12/dist-packages (2.2.2)\n",
38
+ "Requirement already satisfied: matplotlib in /usr/local/lib/python3.12/dist-packages (3.10.0)\n",
39
+ "Requirement already satisfied: seaborn in /usr/local/lib/python3.12/dist-packages (0.13.2)\n",
40
+ "Requirement already satisfied: numpy in /usr/local/lib/python3.12/dist-packages (2.0.2)\n",
41
+ "Requirement already satisfied: textblob in /usr/local/lib/python3.12/dist-packages (0.19.0)\n",
42
+ "Requirement already satisfied: soupsieve>1.2 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (2.8.3)\n",
43
+ "Requirement already satisfied: typing-extensions>=4.0.0 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (4.15.0)\n",
44
+ "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas) (2.9.0.post0)\n",
45
+ "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.2)\n",
46
+ "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.3)\n",
47
+ "Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.3.3)\n",
48
+ "Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (0.12.1)\n",
49
+ "Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (4.62.0)\n",
50
+ "Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.5.0)\n",
51
+ "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (26.0)\n",
52
+ "Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (11.3.0)\n",
53
+ "Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (3.3.2)\n",
54
+ "Requirement already satisfied: nltk>=3.9 in /usr/local/lib/python3.12/dist-packages (from textblob) (3.9.1)\n",
55
+ "Requirement already satisfied: click in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (8.3.1)\n",
56
+ "Requirement already satisfied: joblib in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (1.5.3)\n",
57
+ "Requirement already satisfied: regex>=2021.8.3 in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (2025.11.3)\n",
58
+ "Requirement already satisfied: tqdm in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (4.67.3)\n",
59
+ "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)\n"
60
+ ]
61
+ }
62
+ ],
63
+ "source": [
64
+ "!pip install beautifulsoup4 pandas matplotlib seaborn numpy textblob"
65
+ ]
66
+ },
67
+ {
68
+ "cell_type": "markdown",
69
+ "metadata": {
70
+ "id": "lquNYCbfL9IM"
71
+ },
72
+ "source": [
73
+ "## **2.** ⛏ Web-scrape all book titles, prices, and ratings from books.toscrape.com"
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "markdown",
78
+ "metadata": {
79
+ "id": "0IWuNpxxYDJF"
80
+ },
81
+ "source": [
82
+ "### *a. Initial setup*\n",
83
+ "Define the base url of the website you will scrape as well as how and what you will scrape"
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "execution_count": 2,
89
+ "metadata": {
90
+ "id": "91d52125"
91
+ },
92
+ "outputs": [],
93
+ "source": [
94
+ "import requests\n",
95
+ "from bs4 import BeautifulSoup\n",
96
+ "import pandas as pd\n",
97
+ "import time\n",
98
+ "\n",
99
+ "base_url = \"https://books.toscrape.com/catalogue/page-{}.html\"\n",
100
+ "headers = {\"User-Agent\": \"Mozilla/5.0\"}\n",
101
+ "\n",
102
+ "titles, prices, ratings = [], [], []"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "markdown",
107
+ "metadata": {
108
+ "id": "oCdTsin2Yfp3"
109
+ },
110
+ "source": [
111
+ "### *b. Fill titles, prices, and ratings from the web pages*"
112
+ ]
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "execution_count": 3,
117
+ "metadata": {
118
+ "id": "xqO5Y3dnYhxt"
119
+ },
120
+ "outputs": [],
121
+ "source": [
122
+ "# Loop through all 50 pages\n",
123
+ "for page in range(1, 51):\n",
124
+ " url = base_url.format(page)\n",
125
+ " response = requests.get(url, headers=headers)\n",
126
+ " soup = BeautifulSoup(response.content, \"html.parser\")\n",
127
+ " books = soup.find_all(\"article\", class_=\"product_pod\")\n",
128
+ "\n",
129
+ " for book in books:\n",
130
+ " titles.append(book.h3.a[\"title\"])\n",
131
+ " prices.append(float(book.find(\"p\", class_=\"price_color\").text[1:]))\n",
132
+ " ratings.append(book.p.get(\"class\")[1])\n",
133
+ "\n",
134
+ " time.sleep(0.5) # polite scraping delay"
135
+ ]
136
+ },
137
+ {
138
+ "cell_type": "markdown",
139
+ "metadata": {
140
+ "id": "T0TOeRC4Yrnn"
141
+ },
142
+ "source": [
143
+ "### *c. ✋🏻🛑⛔️ Create a dataframe df_books that contains the now complete \"title\", \"price\", and \"rating\" objects*"
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "execution_count": 4,
149
+ "metadata": {
150
+ "id": "azPR5NjHqphK"
151
+ },
152
+ "outputs": [],
153
+ "source": [
154
+ "df_books = pd.DataFrame({\n",
155
+ " \"title\": titles,\n",
156
+ " \"price\": prices,\n",
157
+ " \"rating\": ratings\n",
158
+ "})"
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "markdown",
163
+ "metadata": {
164
+ "id": "duI5dv3CZYvF"
165
+ },
166
+ "source": [
167
+ "### *d. Save web-scraped dataframe either as a CSV or Excel file*"
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "execution_count": 5,
173
+ "metadata": {
174
+ "id": "lC1U_YHtZifh"
175
+ },
176
+ "outputs": [],
177
+ "source": [
178
+ "# 💾 Save to CSV\n",
179
+ "df_books.to_csv(\"books_data.csv\", index=False)\n",
180
+ "\n",
181
+ "# 💾 Or save to Excel\n",
182
+ "# df_books.to_excel(\"books_data.xlsx\", index=False)"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "markdown",
187
+ "metadata": {
188
+ "id": "qMjRKMBQZlJi"
189
+ },
190
+ "source": [
191
+ "### *e. ✋🏻🛑⛔️ View first fiew lines*"
192
+ ]
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "execution_count": 6,
197
+ "metadata": {
198
+ "colab": {
199
+ "base_uri": "https://localhost:8080/",
200
+ "height": 204
201
+ },
202
+ "id": "O_wIvTxYZqCK",
203
+ "outputId": "de83f95f-f4ff-462b-af6a-7de5f0b5f339"
204
+ },
205
+ "outputs": [
206
+ {
207
+ "output_type": "execute_result",
208
+ "data": {
209
+ "text/plain": [
210
+ " title price rating\n",
211
+ "0 A Light in the Attic 51.77 Three\n",
212
+ "1 Tipping the Velvet 53.74 One\n",
213
+ "2 Soumission 50.10 One\n",
214
+ "3 Sharp Objects 47.82 Four\n",
215
+ "4 Sapiens: A Brief History of Humankind 54.23 Five"
216
+ ],
217
+ "text/html": [
218
+ "\n",
219
+ " <div id=\"df-8e09c83b-c6b4-40ba-8ba8-ce837ed8c774\" class=\"colab-df-container\">\n",
220
+ " <div>\n",
221
+ "<style scoped>\n",
222
+ " .dataframe tbody tr th:only-of-type {\n",
223
+ " vertical-align: middle;\n",
224
+ " }\n",
225
+ "\n",
226
+ " .dataframe tbody tr th {\n",
227
+ " vertical-align: top;\n",
228
+ " }\n",
229
+ "\n",
230
+ " .dataframe thead th {\n",
231
+ " text-align: right;\n",
232
+ " }\n",
233
+ "</style>\n",
234
+ "<table border=\"1\" class=\"dataframe\">\n",
235
+ " <thead>\n",
236
+ " <tr style=\"text-align: right;\">\n",
237
+ " <th></th>\n",
238
+ " <th>title</th>\n",
239
+ " <th>price</th>\n",
240
+ " <th>rating</th>\n",
241
+ " </tr>\n",
242
+ " </thead>\n",
243
+ " <tbody>\n",
244
+ " <tr>\n",
245
+ " <th>0</th>\n",
246
+ " <td>A Light in the Attic</td>\n",
247
+ " <td>51.77</td>\n",
248
+ " <td>Three</td>\n",
249
+ " </tr>\n",
250
+ " <tr>\n",
251
+ " <th>1</th>\n",
252
+ " <td>Tipping the Velvet</td>\n",
253
+ " <td>53.74</td>\n",
254
+ " <td>One</td>\n",
255
+ " </tr>\n",
256
+ " <tr>\n",
257
+ " <th>2</th>\n",
258
+ " <td>Soumission</td>\n",
259
+ " <td>50.10</td>\n",
260
+ " <td>One</td>\n",
261
+ " </tr>\n",
262
+ " <tr>\n",
263
+ " <th>3</th>\n",
264
+ " <td>Sharp Objects</td>\n",
265
+ " <td>47.82</td>\n",
266
+ " <td>Four</td>\n",
267
+ " </tr>\n",
268
+ " <tr>\n",
269
+ " <th>4</th>\n",
270
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
271
+ " <td>54.23</td>\n",
272
+ " <td>Five</td>\n",
273
+ " </tr>\n",
274
+ " </tbody>\n",
275
+ "</table>\n",
276
+ "</div>\n",
277
+ " <div class=\"colab-df-buttons\">\n",
278
+ "\n",
279
+ " <div class=\"colab-df-container\">\n",
280
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-8e09c83b-c6b4-40ba-8ba8-ce837ed8c774')\"\n",
281
+ " title=\"Convert this dataframe to an interactive table.\"\n",
282
+ " style=\"display:none;\">\n",
283
+ "\n",
284
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
285
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
286
+ " </svg>\n",
287
+ " </button>\n",
288
+ "\n",
289
+ " <style>\n",
290
+ " .colab-df-container {\n",
291
+ " display:flex;\n",
292
+ " gap: 12px;\n",
293
+ " }\n",
294
+ "\n",
295
+ " .colab-df-convert {\n",
296
+ " background-color: #E8F0FE;\n",
297
+ " border: none;\n",
298
+ " border-radius: 50%;\n",
299
+ " cursor: pointer;\n",
300
+ " display: none;\n",
301
+ " fill: #1967D2;\n",
302
+ " height: 32px;\n",
303
+ " padding: 0 0 0 0;\n",
304
+ " width: 32px;\n",
305
+ " }\n",
306
+ "\n",
307
+ " .colab-df-convert:hover {\n",
308
+ " background-color: #E2EBFA;\n",
309
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
310
+ " fill: #174EA6;\n",
311
+ " }\n",
312
+ "\n",
313
+ " .colab-df-buttons div {\n",
314
+ " margin-bottom: 4px;\n",
315
+ " }\n",
316
+ "\n",
317
+ " [theme=dark] .colab-df-convert {\n",
318
+ " background-color: #3B4455;\n",
319
+ " fill: #D2E3FC;\n",
320
+ " }\n",
321
+ "\n",
322
+ " [theme=dark] .colab-df-convert:hover {\n",
323
+ " background-color: #434B5C;\n",
324
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
325
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
326
+ " fill: #FFFFFF;\n",
327
+ " }\n",
328
+ " </style>\n",
329
+ "\n",
330
+ " <script>\n",
331
+ " const buttonEl =\n",
332
+ " document.querySelector('#df-8e09c83b-c6b4-40ba-8ba8-ce837ed8c774 button.colab-df-convert');\n",
333
+ " buttonEl.style.display =\n",
334
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
335
+ "\n",
336
+ " async function convertToInteractive(key) {\n",
337
+ " const element = document.querySelector('#df-8e09c83b-c6b4-40ba-8ba8-ce837ed8c774');\n",
338
+ " const dataTable =\n",
339
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
340
+ " [key], {});\n",
341
+ " if (!dataTable) return;\n",
342
+ "\n",
343
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
344
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
345
+ " + ' to learn more about interactive tables.';\n",
346
+ " element.innerHTML = '';\n",
347
+ " dataTable['output_type'] = 'display_data';\n",
348
+ " await google.colab.output.renderOutput(dataTable, element);\n",
349
+ " const docLink = document.createElement('div');\n",
350
+ " docLink.innerHTML = docLinkHtml;\n",
351
+ " element.appendChild(docLink);\n",
352
+ " }\n",
353
+ " </script>\n",
354
+ " </div>\n",
355
+ "\n",
356
+ "\n",
357
+ " </div>\n",
358
+ " </div>\n"
359
+ ],
360
+ "application/vnd.google.colaboratory.intrinsic+json": {
361
+ "type": "dataframe",
362
+ "variable_name": "df_books",
363
+ "summary": "{\n \"name\": \"df_books\",\n \"rows\": 1000,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 999,\n \"samples\": [\n \"The Grownup\",\n \"Persepolis: The Story of a Childhood (Persepolis #1-2)\",\n \"Ayumi's Violin\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"price\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 14.446689669952772,\n \"min\": 10.0,\n \"max\": 59.99,\n \"num_unique_values\": 903,\n \"samples\": [\n 19.73,\n 55.65,\n 46.31\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"One\",\n \"Two\",\n \"Four\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
364
+ }
365
+ },
366
+ "metadata": {},
367
+ "execution_count": 6
368
+ }
369
+ ],
370
+ "source": [
371
+ "df_books.head()"
372
+ ]
373
+ },
374
+ {
375
+ "cell_type": "markdown",
376
+ "metadata": {
377
+ "id": "p-1Pr2szaqLk"
378
+ },
379
+ "source": [
380
+ "## **3.** 🧩 Create a meaningful connection between real & synthetic datasets"
381
+ ]
382
+ },
383
+ {
384
+ "cell_type": "markdown",
385
+ "metadata": {
386
+ "id": "SIaJUGIpaH4V"
387
+ },
388
+ "source": [
389
+ "### *a. Initial setup*"
390
+ ]
391
+ },
392
+ {
393
+ "cell_type": "code",
394
+ "execution_count": 7,
395
+ "metadata": {
396
+ "id": "-gPXGcRPuV_9"
397
+ },
398
+ "outputs": [],
399
+ "source": [
400
+ "import numpy as np\n",
401
+ "import random\n",
402
+ "from datetime import datetime\n",
403
+ "import warnings\n",
404
+ "\n",
405
+ "warnings.filterwarnings(\"ignore\")\n",
406
+ "random.seed(2025)\n",
407
+ "np.random.seed(2025)"
408
+ ]
409
+ },
410
+ {
411
+ "cell_type": "markdown",
412
+ "metadata": {
413
+ "id": "pY4yCoIuaQqp"
414
+ },
415
+ "source": [
416
+ "### *b. Generate popularity scores based on rating (with some randomness) with a generate_popularity_score function*"
417
+ ]
418
+ },
419
+ {
420
+ "cell_type": "code",
421
+ "execution_count": 8,
422
+ "metadata": {
423
+ "id": "mnd5hdAbaNjz"
424
+ },
425
+ "outputs": [],
426
+ "source": [
427
+ "def generate_popularity_score(rating):\n",
428
+ " base = {\"One\": 2, \"Two\": 3, \"Three\": 3, \"Four\": 4, \"Five\": 4}.get(rating, 3)\n",
429
+ " trend_factor = random.choices([-1, 0, 1], weights=[1, 3, 2])[0]\n",
430
+ " return int(np.clip(base + trend_factor, 1, 5))"
431
+ ]
432
+ },
433
+ {
434
+ "cell_type": "markdown",
435
+ "metadata": {
436
+ "id": "n4-TaNTFgPak"
437
+ },
438
+ "source": [
439
+ "### *c. ✋🏻🛑⛔️ Run the function to create a \"popularity_score\" column from \"rating\"*"
440
+ ]
441
+ },
442
+ {
443
+ "cell_type": "code",
444
+ "execution_count": 9,
445
+ "metadata": {
446
+ "id": "zaTMGv0NrqAP"
447
+ },
448
+ "outputs": [],
449
+ "source": [
450
+ "df_books[\"popularity_score\"] = df_books[\"rating\"].apply(generate_popularity_score)"
451
+ ]
452
+ },
453
+ {
454
+ "cell_type": "markdown",
455
+ "metadata": {
456
+ "id": "HnngRNTgacYt"
457
+ },
458
+ "source": [
459
+ "### *d. Decide on the sentiment_label based on the popularity score with a get_sentiment function*"
460
+ ]
461
+ },
462
+ {
463
+ "cell_type": "code",
464
+ "execution_count": 10,
465
+ "metadata": {
466
+ "id": "kUtWmr8maZLZ"
467
+ },
468
+ "outputs": [],
469
+ "source": [
470
+ "def get_sentiment(popularity_score):\n",
471
+ " if popularity_score <= 2:\n",
472
+ " return \"negative\"\n",
473
+ " elif popularity_score == 3:\n",
474
+ " return \"neutral\"\n",
475
+ " else:\n",
476
+ " return \"positive\""
477
+ ]
478
+ },
479
+ {
480
+ "cell_type": "markdown",
481
+ "metadata": {
482
+ "id": "HF9F9HIzgT7Z"
483
+ },
484
+ "source": [
485
+ "### *e. ✋🏻🛑⛔️ Run the function to create a \"sentiment_label\" column from \"popularity_score\"*"
486
+ ]
487
+ },
488
+ {
489
+ "cell_type": "code",
490
+ "execution_count": 11,
491
+ "metadata": {
492
+ "id": "_jZG8Hljrx9L"
493
+ },
494
+ "outputs": [],
495
+ "source": [
496
+ "df_books[\"sentiment_label\"] = df_books[\"popularity_score\"].apply(get_sentiment)"
497
+ ]
498
+ },
499
+ {
500
+ "cell_type": "markdown",
501
+ "metadata": {
502
+ "id": "T8AdKkmASq9a"
503
+ },
504
+ "source": [
505
+ "## **4.** 📈 Generate synthetic book sales data of 18 months"
506
+ ]
507
+ },
508
+ {
509
+ "cell_type": "markdown",
510
+ "metadata": {
511
+ "id": "OhXbdGD5fH0c"
512
+ },
513
+ "source": [
514
+ "### *a. Create a generate_sales_profit function that would generate sales patterns based on sentiment_label (with some randomness)*"
515
+ ]
516
+ },
517
+ {
518
+ "cell_type": "code",
519
+ "execution_count": 12,
520
+ "metadata": {
521
+ "id": "qkVhYPXGbgEn"
522
+ },
523
+ "outputs": [],
524
+ "source": [
525
+ "def generate_sales_profile(sentiment):\n",
526
+ " months = pd.date_range(end=datetime.today(), periods=18, freq=\"M\")\n",
527
+ "\n",
528
+ " if sentiment == \"positive\":\n",
529
+ " base = random.randint(200, 300)\n",
530
+ " trend = np.linspace(base, base + random.randint(20, 60), len(months))\n",
531
+ " elif sentiment == \"negative\":\n",
532
+ " base = random.randint(20, 80)\n",
533
+ " trend = np.linspace(base, base - random.randint(10, 30), len(months))\n",
534
+ " else: # neutral\n",
535
+ " base = random.randint(80, 160)\n",
536
+ " trend = np.full(len(months), base + random.randint(-10, 10))\n",
537
+ "\n",
538
+ " seasonality = 10 * np.sin(np.linspace(0, 3 * np.pi, len(months)))\n",
539
+ " noise = np.random.normal(0, 5, len(months))\n",
540
+ " monthly_sales = np.clip(trend + seasonality + noise, a_min=0, a_max=None).astype(int)\n",
541
+ "\n",
542
+ " return list(zip(months.strftime(\"%Y-%m\"), monthly_sales))"
543
+ ]
544
+ },
545
+ {
546
+ "cell_type": "markdown",
547
+ "metadata": {
548
+ "id": "L2ak1HlcgoTe"
549
+ },
550
+ "source": [
551
+ "### *b. Run the function as part of building sales_data*"
552
+ ]
553
+ },
554
+ {
555
+ "cell_type": "code",
556
+ "execution_count": 13,
557
+ "metadata": {
558
+ "id": "SlJ24AUafoDB"
559
+ },
560
+ "outputs": [],
561
+ "source": [
562
+ "sales_data = []\n",
563
+ "for _, row in df_books.iterrows():\n",
564
+ " records = generate_sales_profile(row[\"sentiment_label\"])\n",
565
+ " for month, units in records:\n",
566
+ " sales_data.append({\n",
567
+ " \"title\": row[\"title\"],\n",
568
+ " \"month\": month,\n",
569
+ " \"units_sold\": units,\n",
570
+ " \"sentiment_label\": row[\"sentiment_label\"]\n",
571
+ " })"
572
+ ]
573
+ },
574
+ {
575
+ "cell_type": "markdown",
576
+ "metadata": {
577
+ "id": "4IXZKcCSgxnq"
578
+ },
579
+ "source": [
580
+ "### *c. ✋🏻🛑⛔️ Create a df_sales DataFrame from sales_data*"
581
+ ]
582
+ },
583
+ {
584
+ "cell_type": "code",
585
+ "execution_count": 14,
586
+ "metadata": {
587
+ "id": "NW-AjejTsIPG"
588
+ },
589
+ "outputs": [],
590
+ "source": [
591
+ "df_sales = pd.DataFrame(sales_data)"
592
+ ]
593
+ },
594
+ {
595
+ "cell_type": "markdown",
596
+ "metadata": {
597
+ "id": "EhIjz9WohAmZ"
598
+ },
599
+ "source": [
600
+ "### *d. Save df_sales as synthetic_sales_data.csv & view first few lines*"
601
+ ]
602
+ },
603
+ {
604
+ "cell_type": "code",
605
+ "execution_count": 15,
606
+ "metadata": {
607
+ "colab": {
608
+ "base_uri": "https://localhost:8080/"
609
+ },
610
+ "id": "MzbZvLcAhGaH",
611
+ "outputId": "82feb55d-4977-429c-be89-2b44dd2439a0"
612
+ },
613
+ "outputs": [
614
+ {
615
+ "output_type": "stream",
616
+ "name": "stdout",
617
+ "text": [
618
+ " title month units_sold sentiment_label\n",
619
+ "0 A Light in the Attic 2024-09 100 neutral\n",
620
+ "1 A Light in the Attic 2024-10 109 neutral\n",
621
+ "2 A Light in the Attic 2024-11 102 neutral\n",
622
+ "3 A Light in the Attic 2024-12 107 neutral\n",
623
+ "4 A Light in the Attic 2025-01 108 neutral\n"
624
+ ]
625
+ }
626
+ ],
627
+ "source": [
628
+ "df_sales.to_csv(\"synthetic_sales_data.csv\", index=False)\n",
629
+ "\n",
630
+ "print(df_sales.head())"
631
+ ]
632
+ },
633
+ {
634
+ "cell_type": "markdown",
635
+ "metadata": {
636
+ "id": "7g9gqBgQMtJn"
637
+ },
638
+ "source": [
639
+ "## **5.** 🎯 Generate synthetic customer reviews"
640
+ ]
641
+ },
642
+ {
643
+ "cell_type": "markdown",
644
+ "metadata": {
645
+ "id": "Gi4y9M9KuDWx"
646
+ },
647
+ "source": [
648
+ "### *a. ✋🏻🛑⛔️ Ask ChatGPT to create a list of 50 distinct generic book review texts for the sentiment labels \"positive\", \"neutral\", and \"negative\" called synthetic_reviews_by_sentiment*"
649
+ ]
650
+ },
651
+ {
652
+ "cell_type": "code",
653
+ "execution_count": 17,
654
+ "metadata": {
655
+ "id": "b3cd2a50"
656
+ },
657
+ "outputs": [],
658
+ "source": [
659
+ "synthetic_reviews_by_sentiment = {\n",
660
+ " \"positive\": [\n",
661
+ " \"A beautifully written story that pulled me in from page one.\",\n",
662
+ " \"I couldn't put this down—fast-paced, emotional, and satisfying.\",\n",
663
+ " \"The characters felt so real, I miss them already.\",\n",
664
+ " \"A smart, heartfelt read with a payoff that truly lands.\",\n",
665
+ " \"Gorgeous prose and a plot that kept surprising me.\",\n",
666
+ " \"This book restored my faith in storytelling—fantastic.\",\n",
667
+ " \"An uplifting, immersive journey that stayed with me for days.\",\n",
668
+ " \"The world-building is vivid without ever slowing the story.\",\n",
669
+ " \"A tender, thoughtful novel with moments that made me tear up.\",\n",
670
+ " \"Every chapter made me want to keep going—excellent pacing.\",\n",
671
+ " \"A rare book where the ending feels earned and unforgettable.\",\n",
672
+ " \"I loved the dialogue—sharp, funny, and full of personality.\",\n",
673
+ " \"A compelling blend of mystery and emotion—highly recommend.\",\n",
674
+ " \"The themes were handled with care and real insight.\",\n",
675
+ " \"An instant favorite—I'll be recommending this to everyone.\",\n",
676
+ " \"The plot twists were clever without feeling cheap.\",\n",
677
+ " \"A powerful story told with confidence and heart.\",\n",
678
+ " \"I laughed, I cried, and I immediately wanted to reread it.\",\n",
679
+ " \"Strong voice, strong characters, and a wonderfully satisfying arc.\",\n",
680
+ " \"A gripping read with surprising depth and warmth.\",\n",
681
+ " \"This was exactly what I needed—comforting and inspiring.\",\n",
682
+ " \"The author’s writing style is addictive and beautifully precise.\",\n",
683
+ " \"A moving exploration of love, loss, and hope.\",\n",
684
+ " \"I was completely transported—this is storytelling at its best.\",\n",
685
+ " \"A delightful surprise—fresh, original, and genuinely engaging.\",\n",
686
+ " \"The main character’s growth felt authentic and rewarding.\",\n",
687
+ " \"Such an atmospheric book—I could picture every scene.\",\n",
688
+ " \"A wonderful mix of humor and heart that never felt forced.\",\n",
689
+ " \"I devoured it in two sittings—so entertaining.\",\n",
690
+ " \"An emotionally rich novel that still keeps the plot tight.\",\n",
691
+ " \"Fantastic character chemistry and a plot that kept me hooked.\",\n",
692
+ " \"The writing is elegant, and the story is even better.\",\n",
693
+ " \"A masterpiece of pacing—never a dull moment.\",\n",
694
+ " \"This book has one of the best openings I've read in ages.\",\n",
695
+ " \"It’s rare to find a story this both fun and meaningful.\",\n",
696
+ " \"The ending made me smile—so satisfying and well done.\",\n",
697
+ " \"A thrilling ride with real emotional stakes.\",\n",
698
+ " \"Beautifully layered storytelling with memorable scenes.\",\n",
699
+ " \"An engaging plot and a voice that feels fresh and confident.\",\n",
700
+ " \"The side characters were just as strong as the lead—loved it.\",\n",
701
+ " \"I appreciated how thoughtful and nuanced the themes were.\",\n",
702
+ " \"A heartfelt page-turner that’s hard to forget.\",\n",
703
+ " \"Clever, charming, and surprisingly profound.\",\n",
704
+ " \"A stunning debut—can’t wait to read more from this author.\",\n",
705
+ " \"The suspense was perfect and the resolution was rewarding.\",\n",
706
+ " \"I enjoyed every moment—pure reading joy.\",\n",
707
+ " \"A captivating story with writing that sparkles.\",\n",
708
+ " \"The emotional beats hit perfectly—so well crafted.\",\n",
709
+ " \"This book exceeded my expectations in every way.\",\n",
710
+ " \"An unforgettable read—highly recommended.\"\n",
711
+ " ],\n",
712
+ " \"neutral\": [\n",
713
+ " \"It was an okay read—some strong parts, some slower stretches.\",\n",
714
+ " \"Interesting premise, but the execution didn’t fully wow me.\",\n",
715
+ " \"I enjoyed it enough, though it didn’t leave a big impression.\",\n",
716
+ " \"A solid book overall, just not quite my favorite.\",\n",
717
+ " \"The writing was good, but the plot felt a bit predictable.\",\n",
718
+ " \"Some chapters were engaging, others dragged for me.\",\n",
719
+ " \"Not bad, not amazing—just a decent way to spend an afternoon.\",\n",
720
+ " \"The characters were fine, though I wanted more depth.\",\n",
721
+ " \"I liked the idea more than the story itself.\",\n",
722
+ " \"A competently written book that didn’t take many risks.\",\n",
723
+ " \"It held my attention, but I wasn’t eager to rush back to it.\",\n",
724
+ " \"The pacing was uneven—strong start, slower middle.\",\n",
725
+ " \"The ending was fine, though I expected something bigger.\",\n",
726
+ " \"There were a few great scenes, but also some filler.\",\n",
727
+ " \"I can see why people like it, but it wasn’t for me.\",\n",
728
+ " \"The story was straightforward and easy to follow.\",\n",
729
+ " \"Good writing, but the tone didn’t always work for me.\",\n",
730
+ " \"It had moments of charm, but didn’t fully click overall.\",\n",
731
+ " \"A pleasant read, though I probably won’t reread it.\",\n",
732
+ " \"The plot was okay, but I wanted more tension.\",\n",
733
+ " \"Some characters stood out, while others felt flat.\",\n",
734
+ " \"It started strong, then became more average as it went on.\",\n",
735
+ " \"The world-building was interesting but not fully explored.\",\n",
736
+ " \"A decent story with a few memorable moments.\",\n",
737
+ " \"I finished it, but I wasn’t blown away.\",\n",
738
+ " \"It delivered what it promised—nothing more, nothing less.\",\n",
739
+ " \"The writing style was fine, though not particularly distinctive.\",\n",
740
+ " \"The middle section slowed down the momentum a lot.\",\n",
741
+ " \"A good concept, but the ending felt a little rushed.\",\n",
742
+ " \"It was readable, but I didn’t connect emotionally.\",\n",
743
+ " \"Some of the dialogue felt natural; some felt stiff.\",\n",
744
+ " \"I liked parts of it, but overall it was just okay.\",\n",
745
+ " \"A middle-of-the-road read with a few highlights.\",\n",
746
+ " \"It had potential, but didn’t fully deliver for me.\",\n",
747
+ " \"There’s nothing wrong with it—just not memorable.\",\n",
748
+ " \"The story was fine, but I wanted more character development.\",\n",
749
+ " \"An easy read, though the stakes felt low.\",\n",
750
+ " \"I didn’t dislike it, but I wasn’t excited either.\",\n",
751
+ " \"The plot moved along, but it rarely surprised me.\",\n",
752
+ " \"It had a clear message, though it felt a bit on-the-nose.\",\n",
753
+ " \"Some chapters were compelling, others felt repetitive.\",\n",
754
+ " \"I liked the setting more than the characters.\",\n",
755
+ " \"A decent book that I’d recommend only to certain readers.\",\n",
756
+ " \"I’m glad I read it, but I won’t be talking about it much.\",\n",
757
+ " \"It was entertaining enough, though not standout.\",\n",
758
+ " \"The writing was smooth, but the story felt familiar.\",\n",
759
+ " \"It had a few good twists, but I guessed most of them.\",\n",
760
+ " \"Not a waste of time—just not a must-read either.\",\n",
761
+ " \"A fine addition to the genre, but not exceptional.\",\n",
762
+ " \"Overall: solid, but not remarkable.\"\n",
763
+ " ],\n",
764
+ " \"negative\": [\n",
765
+ " \"I struggled to get into this—nothing really grabbed me.\",\n",
766
+ " \"The pacing was slow and the story felt stretched out.\",\n",
767
+ " \"I wanted to like it, but the characters felt flat.\",\n",
768
+ " \"The plot was confusing and hard to stay invested in.\",\n",
769
+ " \"It felt predictable, and the twists didn’t land for me.\",\n",
770
+ " \"The writing style just didn’t work—I kept losing focus.\",\n",
771
+ " \"I finished it, but only out of determination.\",\n",
772
+ " \"Too many clichés and not enough originality.\",\n",
773
+ " \"The dialogue felt unnatural and pulled me out of the story.\",\n",
774
+ " \"The middle dragged so much that I almost DNF’d it.\",\n",
775
+ " \"I found the main character difficult to root for.\",\n",
776
+ " \"The story had potential, but the execution was disappointing.\",\n",
777
+ " \"The tone was inconsistent and made it hard to enjoy.\",\n",
778
+ " \"The ending felt rushed and unsatisfying.\",\n",
779
+ " \"A lot happens, but none of it felt meaningful.\",\n",
780
+ " \"The plot holes made it hard to take seriously.\",\n",
781
+ " \"I didn’t connect with the characters at all.\",\n",
782
+ " \"It was repetitive and could have been much shorter.\",\n",
783
+ " \"The writing felt messy and unclear in places.\",\n",
784
+ " \"The book didn’t live up to the hype for me.\",\n",
785
+ " \"I kept waiting for it to get better, but it never did.\",\n",
786
+ " \"The twists felt forced rather than clever.\",\n",
787
+ " \"The story was dull and lacked emotional impact.\",\n",
788
+ " \"Some scenes were unnecessarily long and added nothing.\",\n",
789
+ " \"It felt like the author didn’t know how to end it.\",\n",
790
+ " \"The characterization was shallow and inconsistent.\",\n",
791
+ " \"I found myself skimming just to get through it.\",\n",
792
+ " \"The plot wandered without a clear direction.\",\n",
793
+ " \"It tried to be deep, but it came off as preachy.\",\n",
794
+ " \"The conflict felt artificial and unconvincing.\",\n",
795
+ " \"The writing was awkward and distracting.\",\n",
796
+ " \"I couldn’t suspend disbelief—too many unrealistic moments.\",\n",
797
+ " \"The world-building was thin and didn’t make sense.\",\n",
798
+ " \"The stakes never felt real, so I didn’t care what happened.\",\n",
799
+ " \"The emotional moments felt unearned.\",\n",
800
+ " \"The book was more frustrating than enjoyable.\",\n",
801
+ " \"The characters made decisions that didn’t make sense.\",\n",
802
+ " \"The story relied too much on convenient coincidences.\",\n",
803
+ " \"I didn’t like the pacing—slow start and abrupt finish.\",\n",
804
+ " \"It felt like a first draft that needed heavy editing.\",\n",
805
+ " \"The plot was bland and offered nothing new.\",\n",
806
+ " \"I was bored for most of it, despite the premise.\",\n",
807
+ " \"The writing felt repetitive and overly descriptive.\",\n",
808
+ " \"The ending left too many loose threads in a bad way.\",\n",
809
+ " \"It was hard to follow and not rewarding to read.\",\n",
810
+ " \"The book promised a lot but delivered very little.\",\n",
811
+ " \"I regret spending time on this one.\",\n",
812
+ " \"This just wasn’t enjoyable—I'd skip it.\",\n",
813
+ " \"I couldn’t get invested, and it felt like a chore.\",\n",
814
+ " \"Disappointing overall—would not recommend.\"\n",
815
+ " ]\n",
816
+ "}"
817
+ ]
818
+ },
819
+ {
820
+ "cell_type": "markdown",
821
+ "metadata": {
822
+ "id": "fQhfVaDmuULT"
823
+ },
824
+ "source": [
825
+ "### *b. Generate 10 reviews per book using random sampling from the corresponding 50*"
826
+ ]
827
+ },
828
+ {
829
+ "cell_type": "code",
830
+ "execution_count": 18,
831
+ "metadata": {
832
+ "id": "l2SRc3PjuTGM"
833
+ },
834
+ "outputs": [],
835
+ "source": [
836
+ "review_rows = []\n",
837
+ "for _, row in df_books.iterrows():\n",
838
+ " title = row['title']\n",
839
+ " sentiment_label = row['sentiment_label']\n",
840
+ " review_pool = synthetic_reviews_by_sentiment[sentiment_label]\n",
841
+ " sampled_reviews = random.sample(review_pool, 10)\n",
842
+ " for review_text in sampled_reviews:\n",
843
+ " review_rows.append({\n",
844
+ " \"title\": title,\n",
845
+ " \"sentiment_label\": sentiment_label,\n",
846
+ " \"review_text\": review_text,\n",
847
+ " \"rating\": row['rating'],\n",
848
+ " \"popularity_score\": row['popularity_score']\n",
849
+ " })"
850
+ ]
851
+ },
852
+ {
853
+ "cell_type": "markdown",
854
+ "metadata": {
855
+ "id": "bmJMXF-Bukdm"
856
+ },
857
+ "source": [
858
+ "### *c. Create the final dataframe df_reviews & save it as synthetic_book_reviews.csv*"
859
+ ]
860
+ },
861
+ {
862
+ "cell_type": "code",
863
+ "execution_count": 19,
864
+ "metadata": {
865
+ "id": "ZUKUqZsuumsp"
866
+ },
867
+ "outputs": [],
868
+ "source": [
869
+ "df_reviews = pd.DataFrame(review_rows)\n",
870
+ "df_reviews.to_csv(\"synthetic_book_reviews.csv\", index=False)"
871
+ ]
872
+ },
873
+ {
874
+ "cell_type": "markdown",
875
+ "source": [
876
+ "### *c. inputs for R*"
877
+ ],
878
+ "metadata": {
879
+ "id": "_602pYUS3gY5"
880
+ }
881
+ },
882
+ {
883
+ "cell_type": "code",
884
+ "execution_count": 20,
885
+ "metadata": {
886
+ "colab": {
887
+ "base_uri": "https://localhost:8080/"
888
+ },
889
+ "id": "3946e521",
890
+ "outputId": "4f3c942b-cfd3-4259-fedb-3dc75e4008e9"
891
+ },
892
+ "outputs": [
893
+ {
894
+ "output_type": "stream",
895
+ "name": "stdout",
896
+ "text": [
897
+ "✅ Wrote synthetic_title_level_features.csv\n",
898
+ "✅ Wrote synthetic_monthly_revenue_series.csv\n"
899
+ ]
900
+ }
901
+ ],
902
+ "source": [
903
+ "import numpy as np\n",
904
+ "\n",
905
+ "def _safe_num(s):\n",
906
+ " return pd.to_numeric(\n",
907
+ " pd.Series(s).astype(str).str.replace(r\"[^0-9.]\", \"\", regex=True),\n",
908
+ " errors=\"coerce\"\n",
909
+ " )\n",
910
+ "\n",
911
+ "# --- Clean book metadata (price/rating) ---\n",
912
+ "df_books_r = df_books.copy()\n",
913
+ "if \"price\" in df_books_r.columns:\n",
914
+ " df_books_r[\"price\"] = _safe_num(df_books_r[\"price\"])\n",
915
+ "if \"rating\" in df_books_r.columns:\n",
916
+ " df_books_r[\"rating\"] = _safe_num(df_books_r[\"rating\"])\n",
917
+ "\n",
918
+ "df_books_r[\"title\"] = df_books_r[\"title\"].astype(str).str.strip()\n",
919
+ "\n",
920
+ "# --- Clean sales ---\n",
921
+ "df_sales_r = df_sales.copy()\n",
922
+ "df_sales_r[\"title\"] = df_sales_r[\"title\"].astype(str).str.strip()\n",
923
+ "df_sales_r[\"month\"] = pd.to_datetime(df_sales_r[\"month\"], errors=\"coerce\")\n",
924
+ "df_sales_r[\"units_sold\"] = _safe_num(df_sales_r[\"units_sold\"])\n",
925
+ "\n",
926
+ "# --- Clean reviews ---\n",
927
+ "df_reviews_r = df_reviews.copy()\n",
928
+ "df_reviews_r[\"title\"] = df_reviews_r[\"title\"].astype(str).str.strip()\n",
929
+ "df_reviews_r[\"sentiment_label\"] = df_reviews_r[\"sentiment_label\"].astype(str).str.lower().str.strip()\n",
930
+ "if \"rating\" in df_reviews_r.columns:\n",
931
+ " df_reviews_r[\"rating\"] = _safe_num(df_reviews_r[\"rating\"])\n",
932
+ "if \"popularity_score\" in df_reviews_r.columns:\n",
933
+ " df_reviews_r[\"popularity_score\"] = _safe_num(df_reviews_r[\"popularity_score\"])\n",
934
+ "\n",
935
+ "# --- Sentiment shares per title (from reviews) ---\n",
936
+ "sent_counts = (\n",
937
+ " df_reviews_r.groupby([\"title\", \"sentiment_label\"])\n",
938
+ " .size()\n",
939
+ " .unstack(fill_value=0)\n",
940
+ ")\n",
941
+ "for lab in [\"positive\", \"neutral\", \"negative\"]:\n",
942
+ " if lab not in sent_counts.columns:\n",
943
+ " sent_counts[lab] = 0\n",
944
+ "\n",
945
+ "sent_counts[\"total_reviews\"] = sent_counts[[\"positive\", \"neutral\", \"negative\"]].sum(axis=1)\n",
946
+ "den = sent_counts[\"total_reviews\"].replace(0, np.nan)\n",
947
+ "sent_counts[\"share_positive\"] = sent_counts[\"positive\"] / den\n",
948
+ "sent_counts[\"share_neutral\"] = sent_counts[\"neutral\"] / den\n",
949
+ "sent_counts[\"share_negative\"] = sent_counts[\"negative\"] / den\n",
950
+ "sent_counts = sent_counts.reset_index()\n",
951
+ "\n",
952
+ "# --- Sales aggregation per title ---\n",
953
+ "sales_by_title = (\n",
954
+ " df_sales_r.dropna(subset=[\"title\"])\n",
955
+ " .groupby(\"title\", as_index=False)\n",
956
+ " .agg(\n",
957
+ " months_observed=(\"month\", \"nunique\"),\n",
958
+ " avg_units_sold=(\"units_sold\", \"mean\"),\n",
959
+ " total_units_sold=(\"units_sold\", \"sum\"),\n",
960
+ " )\n",
961
+ ")\n",
962
+ "\n",
963
+ "# --- Title-level features (join sales + books + sentiment) ---\n",
964
+ "df_title = (\n",
965
+ " sales_by_title\n",
966
+ " .merge(df_books_r[[\"title\", \"price\", \"rating\"]], on=\"title\", how=\"left\")\n",
967
+ " .merge(sent_counts[[\"title\", \"share_positive\", \"share_neutral\", \"share_negative\", \"total_reviews\"]],\n",
968
+ " on=\"title\", how=\"left\")\n",
969
+ ")\n",
970
+ "\n",
971
+ "df_title[\"avg_revenue\"] = df_title[\"avg_units_sold\"] * df_title[\"price\"]\n",
972
+ "df_title[\"total_revenue\"] = df_title[\"total_units_sold\"] * df_title[\"price\"]\n",
973
+ "\n",
974
+ "df_title.to_csv(\"synthetic_title_level_features.csv\", index=False)\n",
975
+ "print(\"✅ Wrote synthetic_title_level_features.csv\")\n",
976
+ "\n",
977
+ "# --- Monthly revenue series (proxy: units_sold * price) ---\n",
978
+ "monthly_rev = (\n",
979
+ " df_sales_r.merge(df_books_r[[\"title\", \"price\"]], on=\"title\", how=\"left\")\n",
980
+ ")\n",
981
+ "monthly_rev[\"revenue\"] = monthly_rev[\"units_sold\"] * monthly_rev[\"price\"]\n",
982
+ "\n",
983
+ "df_monthly = (\n",
984
+ " monthly_rev.dropna(subset=[\"month\"])\n",
985
+ " .groupby(\"month\", as_index=False)[\"revenue\"]\n",
986
+ " .sum()\n",
987
+ " .rename(columns={\"revenue\": \"total_revenue\"})\n",
988
+ " .sort_values(\"month\")\n",
989
+ ")\n",
990
+ "# if revenue is all NA (e.g., missing price), fallback to units_sold as a teaching proxy\n",
991
+ "if df_monthly[\"total_revenue\"].notna().sum() == 0:\n",
992
+ " df_monthly = (\n",
993
+ " df_sales_r.dropna(subset=[\"month\"])\n",
994
+ " .groupby(\"month\", as_index=False)[\"units_sold\"]\n",
995
+ " .sum()\n",
996
+ " .rename(columns={\"units_sold\": \"total_revenue\"})\n",
997
+ " .sort_values(\"month\")\n",
998
+ " )\n",
999
+ "\n",
1000
+ "df_monthly[\"month\"] = pd.to_datetime(df_monthly[\"month\"], errors=\"coerce\").dt.strftime(\"%Y-%m-%d\")\n",
1001
+ "df_monthly.to_csv(\"synthetic_monthly_revenue_series.csv\", index=False)\n",
1002
+ "print(\"✅ Wrote synthetic_monthly_revenue_series.csv\")\n"
1003
+ ]
1004
+ },
1005
+ {
1006
+ "cell_type": "markdown",
1007
+ "metadata": {
1008
+ "id": "RYvGyVfXuo54"
1009
+ },
1010
+ "source": [
1011
+ "### *d. ✋🏻🛑⛔️ View the first few lines*"
1012
+ ]
1013
+ },
1014
+ {
1015
+ "cell_type": "code",
1016
+ "execution_count": 21,
1017
+ "metadata": {
1018
+ "colab": {
1019
+ "base_uri": "https://localhost:8080/",
1020
+ "height": 204
1021
+ },
1022
+ "id": "xfE8NMqOurKo",
1023
+ "outputId": "feac0935-973e-40ee-8b14-e0b9870fd84d"
1024
+ },
1025
+ "outputs": [
1026
+ {
1027
+ "output_type": "execute_result",
1028
+ "data": {
1029
+ "text/plain": [
1030
+ " title sentiment_label \\\n",
1031
+ "0 A Light in the Attic neutral \n",
1032
+ "1 A Light in the Attic neutral \n",
1033
+ "2 A Light in the Attic neutral \n",
1034
+ "3 A Light in the Attic neutral \n",
1035
+ "4 A Light in the Attic neutral \n",
1036
+ "\n",
1037
+ " review_text rating popularity_score \n",
1038
+ "0 It had a few good twists, but I guessed most o... Three 3 \n",
1039
+ "1 The world-building was interesting but not ful... Three 3 \n",
1040
+ "2 There’s nothing wrong with it—just not memorable. Three 3 \n",
1041
+ "3 I liked the idea more than the story itself. Three 3 \n",
1042
+ "4 It was entertaining enough, though not standout. Three 3 "
1043
+ ],
1044
+ "text/html": [
1045
+ "\n",
1046
+ " <div id=\"df-d1f64279-9dc0-4036-a8ff-719e93174d3a\" class=\"colab-df-container\">\n",
1047
+ " <div>\n",
1048
+ "<style scoped>\n",
1049
+ " .dataframe tbody tr th:only-of-type {\n",
1050
+ " vertical-align: middle;\n",
1051
+ " }\n",
1052
+ "\n",
1053
+ " .dataframe tbody tr th {\n",
1054
+ " vertical-align: top;\n",
1055
+ " }\n",
1056
+ "\n",
1057
+ " .dataframe thead th {\n",
1058
+ " text-align: right;\n",
1059
+ " }\n",
1060
+ "</style>\n",
1061
+ "<table border=\"1\" class=\"dataframe\">\n",
1062
+ " <thead>\n",
1063
+ " <tr style=\"text-align: right;\">\n",
1064
+ " <th></th>\n",
1065
+ " <th>title</th>\n",
1066
+ " <th>sentiment_label</th>\n",
1067
+ " <th>review_text</th>\n",
1068
+ " <th>rating</th>\n",
1069
+ " <th>popularity_score</th>\n",
1070
+ " </tr>\n",
1071
+ " </thead>\n",
1072
+ " <tbody>\n",
1073
+ " <tr>\n",
1074
+ " <th>0</th>\n",
1075
+ " <td>A Light in the Attic</td>\n",
1076
+ " <td>neutral</td>\n",
1077
+ " <td>It had a few good twists, but I guessed most o...</td>\n",
1078
+ " <td>Three</td>\n",
1079
+ " <td>3</td>\n",
1080
+ " </tr>\n",
1081
+ " <tr>\n",
1082
+ " <th>1</th>\n",
1083
+ " <td>A Light in the Attic</td>\n",
1084
+ " <td>neutral</td>\n",
1085
+ " <td>The world-building was interesting but not ful...</td>\n",
1086
+ " <td>Three</td>\n",
1087
+ " <td>3</td>\n",
1088
+ " </tr>\n",
1089
+ " <tr>\n",
1090
+ " <th>2</th>\n",
1091
+ " <td>A Light in the Attic</td>\n",
1092
+ " <td>neutral</td>\n",
1093
+ " <td>There’s nothing wrong with it—just not memorable.</td>\n",
1094
+ " <td>Three</td>\n",
1095
+ " <td>3</td>\n",
1096
+ " </tr>\n",
1097
+ " <tr>\n",
1098
+ " <th>3</th>\n",
1099
+ " <td>A Light in the Attic</td>\n",
1100
+ " <td>neutral</td>\n",
1101
+ " <td>I liked the idea more than the story itself.</td>\n",
1102
+ " <td>Three</td>\n",
1103
+ " <td>3</td>\n",
1104
+ " </tr>\n",
1105
+ " <tr>\n",
1106
+ " <th>4</th>\n",
1107
+ " <td>A Light in the Attic</td>\n",
1108
+ " <td>neutral</td>\n",
1109
+ " <td>It was entertaining enough, though not standout.</td>\n",
1110
+ " <td>Three</td>\n",
1111
+ " <td>3</td>\n",
1112
+ " </tr>\n",
1113
+ " </tbody>\n",
1114
+ "</table>\n",
1115
+ "</div>\n",
1116
+ " <div class=\"colab-df-buttons\">\n",
1117
+ "\n",
1118
+ " <div class=\"colab-df-container\">\n",
1119
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-d1f64279-9dc0-4036-a8ff-719e93174d3a')\"\n",
1120
+ " title=\"Convert this dataframe to an interactive table.\"\n",
1121
+ " style=\"display:none;\">\n",
1122
+ "\n",
1123
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
1124
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
1125
+ " </svg>\n",
1126
+ " </button>\n",
1127
+ "\n",
1128
+ " <style>\n",
1129
+ " .colab-df-container {\n",
1130
+ " display:flex;\n",
1131
+ " gap: 12px;\n",
1132
+ " }\n",
1133
+ "\n",
1134
+ " .colab-df-convert {\n",
1135
+ " background-color: #E8F0FE;\n",
1136
+ " border: none;\n",
1137
+ " border-radius: 50%;\n",
1138
+ " cursor: pointer;\n",
1139
+ " display: none;\n",
1140
+ " fill: #1967D2;\n",
1141
+ " height: 32px;\n",
1142
+ " padding: 0 0 0 0;\n",
1143
+ " width: 32px;\n",
1144
+ " }\n",
1145
+ "\n",
1146
+ " .colab-df-convert:hover {\n",
1147
+ " background-color: #E2EBFA;\n",
1148
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
1149
+ " fill: #174EA6;\n",
1150
+ " }\n",
1151
+ "\n",
1152
+ " .colab-df-buttons div {\n",
1153
+ " margin-bottom: 4px;\n",
1154
+ " }\n",
1155
+ "\n",
1156
+ " [theme=dark] .colab-df-convert {\n",
1157
+ " background-color: #3B4455;\n",
1158
+ " fill: #D2E3FC;\n",
1159
+ " }\n",
1160
+ "\n",
1161
+ " [theme=dark] .colab-df-convert:hover {\n",
1162
+ " background-color: #434B5C;\n",
1163
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
1164
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
1165
+ " fill: #FFFFFF;\n",
1166
+ " }\n",
1167
+ " </style>\n",
1168
+ "\n",
1169
+ " <script>\n",
1170
+ " const buttonEl =\n",
1171
+ " document.querySelector('#df-d1f64279-9dc0-4036-a8ff-719e93174d3a button.colab-df-convert');\n",
1172
+ " buttonEl.style.display =\n",
1173
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
1174
+ "\n",
1175
+ " async function convertToInteractive(key) {\n",
1176
+ " const element = document.querySelector('#df-d1f64279-9dc0-4036-a8ff-719e93174d3a');\n",
1177
+ " const dataTable =\n",
1178
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
1179
+ " [key], {});\n",
1180
+ " if (!dataTable) return;\n",
1181
+ "\n",
1182
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
1183
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
1184
+ " + ' to learn more about interactive tables.';\n",
1185
+ " element.innerHTML = '';\n",
1186
+ " dataTable['output_type'] = 'display_data';\n",
1187
+ " await google.colab.output.renderOutput(dataTable, element);\n",
1188
+ " const docLink = document.createElement('div');\n",
1189
+ " docLink.innerHTML = docLinkHtml;\n",
1190
+ " element.appendChild(docLink);\n",
1191
+ " }\n",
1192
+ " </script>\n",
1193
+ " </div>\n",
1194
+ "\n",
1195
+ "\n",
1196
+ " </div>\n",
1197
+ " </div>\n"
1198
+ ],
1199
+ "application/vnd.google.colaboratory.intrinsic+json": {
1200
+ "type": "dataframe",
1201
+ "variable_name": "df_reviews",
1202
+ "summary": "{\n \"name\": \"df_reviews\",\n \"rows\": 10000,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 999,\n \"samples\": [\n \"The Grownup\",\n \"Persepolis: The Story of a Childhood (Persepolis #1-2)\",\n \"Ayumi's Violin\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"sentiment_label\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"neutral\",\n \"negative\",\n \"positive\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"review_text\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 150,\n \"samples\": [\n \"This was exactly what I needed\\u2014comforting and inspiring.\",\n \"A lot happens, but none of it felt meaningful.\",\n \"Fantastic character chemistry and a plot that kept me hooked.\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"One\",\n \"Two\",\n \"Four\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"popularity_score\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1,\n \"min\": 1,\n \"max\": 5,\n \"num_unique_values\": 5,\n \"samples\": [\n 2,\n 5,\n 4\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
1203
+ }
1204
+ },
1205
+ "metadata": {},
1206
+ "execution_count": 21
1207
+ }
1208
+ ],
1209
+ "source": [
1210
+ "df_reviews.head()"
1211
+ ]
1212
+ }
1213
+ ],
1214
+ "metadata": {
1215
+ "colab": {
1216
+ "collapsed_sections": [
1217
+ "jpASMyIQMaAq",
1218
+ "lquNYCbfL9IM",
1219
+ "0IWuNpxxYDJF",
1220
+ "oCdTsin2Yfp3",
1221
+ "T0TOeRC4Yrnn",
1222
+ "duI5dv3CZYvF",
1223
+ "qMjRKMBQZlJi",
1224
+ "p-1Pr2szaqLk",
1225
+ "SIaJUGIpaH4V",
1226
+ "pY4yCoIuaQqp",
1227
+ "n4-TaNTFgPak",
1228
+ "HnngRNTgacYt",
1229
+ "HF9F9HIzgT7Z",
1230
+ "T8AdKkmASq9a",
1231
+ "OhXbdGD5fH0c",
1232
+ "L2ak1HlcgoTe",
1233
+ "4IXZKcCSgxnq",
1234
+ "EhIjz9WohAmZ",
1235
+ "Gi4y9M9KuDWx",
1236
+ "fQhfVaDmuULT",
1237
+ "bmJMXF-Bukdm",
1238
+ "RYvGyVfXuo54"
1239
+ ],
1240
+ "provenance": []
1241
+ },
1242
+ "kernelspec": {
1243
+ "display_name": "Python 3",
1244
+ "name": "python3"
1245
+ },
1246
+ "language_info": {
1247
+ "name": "python"
1248
+ }
1249
+ },
1250
+ "nbformat": 4,
1251
+ "nbformat_minor": 0
1252
+ }
Sian_Khoury_Hands_On_Activity_Part_2-2.ipynb ADDED
The diff for this file is too large to render. See raw diff