Phileassss commited on
Commit
d89060d
·
verified ·
1 Parent(s): ff24578

Upload 2 files

Browse files
1_Data_Creation_Phileas_Mazeyrie__Rosset_Seminar_F.ipynb ADDED
@@ -0,0 +1,1290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": "7dfed569-99a5-44c7-b7dd-afabaa3d9257"
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.61.1)\n",
50
+ "Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.4.9)\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": "markdown",
148
+ "source": [
149
+ "**First part to complete**"
150
+ ],
151
+ "metadata": {
152
+ "id": "bPhNHyHQ20KI"
153
+ }
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "execution_count": 4,
158
+ "metadata": {
159
+ "id": "l5FkkNhUYTHh"
160
+ },
161
+ "outputs": [],
162
+ "source": [
163
+ "df_books = pd.DataFrame({\"title\": titles, \"price\": prices, \"rating\": ratings})"
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "markdown",
168
+ "metadata": {
169
+ "id": "duI5dv3CZYvF"
170
+ },
171
+ "source": [
172
+ "### *d. Save web-scraped dataframe either as a CSV or Excel file*"
173
+ ]
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "execution_count": 5,
178
+ "metadata": {
179
+ "id": "lC1U_YHtZifh"
180
+ },
181
+ "outputs": [],
182
+ "source": [
183
+ "# 💾 Save to CSV\n",
184
+ "df_books.to_csv(\"books_data.csv\", index=False)\n",
185
+ "\n",
186
+ "# 💾 Or save to Excel\n",
187
+ "# df_books.to_excel(\"books_data.xlsx\", index=False)"
188
+ ]
189
+ },
190
+ {
191
+ "cell_type": "markdown",
192
+ "metadata": {
193
+ "id": "qMjRKMBQZlJi"
194
+ },
195
+ "source": [
196
+ "### *e. ✋🏻🛑⛔️ View first fiew lines*"
197
+ ]
198
+ },
199
+ {
200
+ "cell_type": "markdown",
201
+ "source": [
202
+ "**Second part to complete**"
203
+ ],
204
+ "metadata": {
205
+ "id": "F54lNj_c3VB2"
206
+ }
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "execution_count": 6,
211
+ "metadata": {
212
+ "colab": {
213
+ "base_uri": "https://localhost:8080/",
214
+ "height": 206
215
+ },
216
+ "id": "O_wIvTxYZqCK",
217
+ "outputId": "28f6f57d-c34a-4d52-f473-eede10139889"
218
+ },
219
+ "outputs": [
220
+ {
221
+ "output_type": "display_data",
222
+ "data": {
223
+ "text/plain": [
224
+ " title price rating\n",
225
+ "0 A Light in the Attic 51.77 Three\n",
226
+ "1 Tipping the Velvet 53.74 One\n",
227
+ "2 Soumission 50.10 One\n",
228
+ "3 Sharp Objects 47.82 Four\n",
229
+ "4 Sapiens: A Brief History of Humankind 54.23 Five"
230
+ ],
231
+ "text/html": [
232
+ "\n",
233
+ " <div id=\"df-30f83754-00af-4649-8299-fd130f8cf24c\" class=\"colab-df-container\">\n",
234
+ " <div>\n",
235
+ "<style scoped>\n",
236
+ " .dataframe tbody tr th:only-of-type {\n",
237
+ " vertical-align: middle;\n",
238
+ " }\n",
239
+ "\n",
240
+ " .dataframe tbody tr th {\n",
241
+ " vertical-align: top;\n",
242
+ " }\n",
243
+ "\n",
244
+ " .dataframe thead th {\n",
245
+ " text-align: right;\n",
246
+ " }\n",
247
+ "</style>\n",
248
+ "<table border=\"1\" class=\"dataframe\">\n",
249
+ " <thead>\n",
250
+ " <tr style=\"text-align: right;\">\n",
251
+ " <th></th>\n",
252
+ " <th>title</th>\n",
253
+ " <th>price</th>\n",
254
+ " <th>rating</th>\n",
255
+ " </tr>\n",
256
+ " </thead>\n",
257
+ " <tbody>\n",
258
+ " <tr>\n",
259
+ " <th>0</th>\n",
260
+ " <td>A Light in the Attic</td>\n",
261
+ " <td>51.77</td>\n",
262
+ " <td>Three</td>\n",
263
+ " </tr>\n",
264
+ " <tr>\n",
265
+ " <th>1</th>\n",
266
+ " <td>Tipping the Velvet</td>\n",
267
+ " <td>53.74</td>\n",
268
+ " <td>One</td>\n",
269
+ " </tr>\n",
270
+ " <tr>\n",
271
+ " <th>2</th>\n",
272
+ " <td>Soumission</td>\n",
273
+ " <td>50.10</td>\n",
274
+ " <td>One</td>\n",
275
+ " </tr>\n",
276
+ " <tr>\n",
277
+ " <th>3</th>\n",
278
+ " <td>Sharp Objects</td>\n",
279
+ " <td>47.82</td>\n",
280
+ " <td>Four</td>\n",
281
+ " </tr>\n",
282
+ " <tr>\n",
283
+ " <th>4</th>\n",
284
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
285
+ " <td>54.23</td>\n",
286
+ " <td>Five</td>\n",
287
+ " </tr>\n",
288
+ " </tbody>\n",
289
+ "</table>\n",
290
+ "</div>\n",
291
+ " <div class=\"colab-df-buttons\">\n",
292
+ "\n",
293
+ " <div class=\"colab-df-container\">\n",
294
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-30f83754-00af-4649-8299-fd130f8cf24c')\"\n",
295
+ " title=\"Convert this dataframe to an interactive table.\"\n",
296
+ " style=\"display:none;\">\n",
297
+ "\n",
298
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
299
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
300
+ " </svg>\n",
301
+ " </button>\n",
302
+ "\n",
303
+ " <style>\n",
304
+ " .colab-df-container {\n",
305
+ " display:flex;\n",
306
+ " gap: 12px;\n",
307
+ " }\n",
308
+ "\n",
309
+ " .colab-df-convert {\n",
310
+ " background-color: #E8F0FE;\n",
311
+ " border: none;\n",
312
+ " border-radius: 50%;\n",
313
+ " cursor: pointer;\n",
314
+ " display: none;\n",
315
+ " fill: #1967D2;\n",
316
+ " height: 32px;\n",
317
+ " padding: 0 0 0 0;\n",
318
+ " width: 32px;\n",
319
+ " }\n",
320
+ "\n",
321
+ " .colab-df-convert:hover {\n",
322
+ " background-color: #E2EBFA;\n",
323
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
324
+ " fill: #174EA6;\n",
325
+ " }\n",
326
+ "\n",
327
+ " .colab-df-buttons div {\n",
328
+ " margin-bottom: 4px;\n",
329
+ " }\n",
330
+ "\n",
331
+ " [theme=dark] .colab-df-convert {\n",
332
+ " background-color: #3B4455;\n",
333
+ " fill: #D2E3FC;\n",
334
+ " }\n",
335
+ "\n",
336
+ " [theme=dark] .colab-df-convert:hover {\n",
337
+ " background-color: #434B5C;\n",
338
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
339
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
340
+ " fill: #FFFFFF;\n",
341
+ " }\n",
342
+ " </style>\n",
343
+ "\n",
344
+ " <script>\n",
345
+ " const buttonEl =\n",
346
+ " document.querySelector('#df-30f83754-00af-4649-8299-fd130f8cf24c button.colab-df-convert');\n",
347
+ " buttonEl.style.display =\n",
348
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
349
+ "\n",
350
+ " async function convertToInteractive(key) {\n",
351
+ " const element = document.querySelector('#df-30f83754-00af-4649-8299-fd130f8cf24c');\n",
352
+ " const dataTable =\n",
353
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
354
+ " [key], {});\n",
355
+ " if (!dataTable) return;\n",
356
+ "\n",
357
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
358
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
359
+ " + ' to learn more about interactive tables.';\n",
360
+ " element.innerHTML = '';\n",
361
+ " dataTable['output_type'] = 'display_data';\n",
362
+ " await google.colab.output.renderOutput(dataTable, element);\n",
363
+ " const docLink = document.createElement('div');\n",
364
+ " docLink.innerHTML = docLinkHtml;\n",
365
+ " element.appendChild(docLink);\n",
366
+ " }\n",
367
+ " </script>\n",
368
+ " </div>\n",
369
+ "\n",
370
+ "\n",
371
+ " </div>\n",
372
+ " </div>\n"
373
+ ],
374
+ "application/vnd.google.colaboratory.intrinsic+json": {
375
+ "type": "dataframe",
376
+ "summary": "{\n \"name\": \"display(df_books\",\n \"rows\": 5,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"Tipping the Velvet\",\n \"Sapiens: A Brief History of Humankind\",\n \"Soumission\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"price\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2.647672562837028,\n \"min\": 47.82,\n \"max\": 54.23,\n \"num_unique_values\": 5,\n \"samples\": [\n 53.74,\n 54.23,\n 50.1\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 4,\n \"samples\": [\n \"One\",\n \"Five\",\n \"Three\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
377
+ }
378
+ },
379
+ "metadata": {}
380
+ }
381
+ ],
382
+ "source": [
383
+ "display(df_books.head())"
384
+ ]
385
+ },
386
+ {
387
+ "cell_type": "markdown",
388
+ "metadata": {
389
+ "id": "p-1Pr2szaqLk"
390
+ },
391
+ "source": [
392
+ "## **3.** 🧩 Create a meaningful connection between real & synthetic datasets"
393
+ ]
394
+ },
395
+ {
396
+ "cell_type": "markdown",
397
+ "metadata": {
398
+ "id": "SIaJUGIpaH4V"
399
+ },
400
+ "source": [
401
+ "### *a. Initial setup*"
402
+ ]
403
+ },
404
+ {
405
+ "cell_type": "code",
406
+ "execution_count": 9,
407
+ "metadata": {
408
+ "id": "-gPXGcRPuV_9"
409
+ },
410
+ "outputs": [],
411
+ "source": [
412
+ "import numpy as np\n",
413
+ "import random\n",
414
+ "from datetime import datetime\n",
415
+ "import warnings\n",
416
+ "\n",
417
+ "warnings.filterwarnings(\"ignore\")\n",
418
+ "random.seed(2025)\n",
419
+ "np.random.seed(2025)"
420
+ ]
421
+ },
422
+ {
423
+ "cell_type": "markdown",
424
+ "metadata": {
425
+ "id": "pY4yCoIuaQqp"
426
+ },
427
+ "source": [
428
+ "### *b. Generate popularity scores based on rating (with some randomness) with a generate_popularity_score function*"
429
+ ]
430
+ },
431
+ {
432
+ "cell_type": "code",
433
+ "execution_count": 10,
434
+ "metadata": {
435
+ "id": "mnd5hdAbaNjz"
436
+ },
437
+ "outputs": [],
438
+ "source": [
439
+ "def generate_popularity_score(rating):\n",
440
+ " base = {\"One\": 2, \"Two\": 3, \"Three\": 3, \"Four\": 4, \"Five\": 4}.get(rating, 3)\n",
441
+ " trend_factor = random.choices([-1, 0, 1], weights=[1, 3, 2])[0]\n",
442
+ " return int(np.clip(base + trend_factor, 1, 5))"
443
+ ]
444
+ },
445
+ {
446
+ "cell_type": "markdown",
447
+ "metadata": {
448
+ "id": "n4-TaNTFgPak"
449
+ },
450
+ "source": [
451
+ "### *c. ✋🏻🛑⛔️ Run the function to create a \"popularity_score\" column from \"rating\"*"
452
+ ]
453
+ },
454
+ {
455
+ "cell_type": "markdown",
456
+ "source": [
457
+ "**Third part to complete**"
458
+ ],
459
+ "metadata": {
460
+ "id": "fP1PDJwE5CdT"
461
+ }
462
+ },
463
+ {
464
+ "cell_type": "code",
465
+ "execution_count": 11,
466
+ "metadata": {
467
+ "id": "V-G3OCUCgR07"
468
+ },
469
+ "outputs": [],
470
+ "source": [
471
+ "df_books['popularity_score'] = df_books['rating'].apply(generate_popularity_score)"
472
+ ]
473
+ },
474
+ {
475
+ "cell_type": "markdown",
476
+ "metadata": {
477
+ "id": "HnngRNTgacYt"
478
+ },
479
+ "source": [
480
+ "### *d. Decide on the sentiment_label based on the popularity score with a get_sentiment function*"
481
+ ]
482
+ },
483
+ {
484
+ "cell_type": "code",
485
+ "execution_count": 12,
486
+ "metadata": {
487
+ "id": "kUtWmr8maZLZ"
488
+ },
489
+ "outputs": [],
490
+ "source": [
491
+ "def get_sentiment(popularity_score):\n",
492
+ " if popularity_score <= 2:\n",
493
+ " return \"negative\"\n",
494
+ " elif popularity_score == 3:\n",
495
+ " return \"neutral\"\n",
496
+ " else:\n",
497
+ " return \"positive\""
498
+ ]
499
+ },
500
+ {
501
+ "cell_type": "markdown",
502
+ "metadata": {
503
+ "id": "HF9F9HIzgT7Z"
504
+ },
505
+ "source": [
506
+ "### *e. ✋🏻🛑⛔️ Run the function to create a \"sentiment_label\" column from \"popularity_score\"*"
507
+ ]
508
+ },
509
+ {
510
+ "cell_type": "code",
511
+ "execution_count": 13,
512
+ "metadata": {
513
+ "id": "tafQj8_7gYCG"
514
+ },
515
+ "outputs": [],
516
+ "source": [
517
+ "df_books['sentiment_label'] = df_books['popularity_score'].apply(get_sentiment)"
518
+ ]
519
+ },
520
+ {
521
+ "cell_type": "markdown",
522
+ "source": [
523
+ "Fiurth thing to complete (!!)"
524
+ ],
525
+ "metadata": {
526
+ "id": "8yC1FQoe5NQb"
527
+ }
528
+ },
529
+ {
530
+ "cell_type": "markdown",
531
+ "metadata": {
532
+ "id": "T8AdKkmASq9a"
533
+ },
534
+ "source": [
535
+ "## **4.** 📈 Generate synthetic book sales data of 18 months"
536
+ ]
537
+ },
538
+ {
539
+ "cell_type": "markdown",
540
+ "metadata": {
541
+ "id": "OhXbdGD5fH0c"
542
+ },
543
+ "source": [
544
+ "### *a. Create a generate_sales_profit function that would generate sales patterns based on sentiment_label (with some randomness)*"
545
+ ]
546
+ },
547
+ {
548
+ "cell_type": "code",
549
+ "execution_count": 14,
550
+ "metadata": {
551
+ "id": "qkVhYPXGbgEn"
552
+ },
553
+ "outputs": [],
554
+ "source": [
555
+ "def generate_sales_profile(sentiment):\n",
556
+ " months = pd.date_range(end=datetime.today(), periods=18, freq=\"M\")\n",
557
+ "\n",
558
+ " if sentiment == \"positive\":\n",
559
+ " base = random.randint(200, 300)\n",
560
+ " trend = np.linspace(base, base + random.randint(20, 60), len(months))\n",
561
+ " elif sentiment == \"negative\":\n",
562
+ " base = random.randint(20, 80)\n",
563
+ " trend = np.linspace(base, base - random.randint(10, 30), len(months))\n",
564
+ " else: # neutral\n",
565
+ " base = random.randint(80, 160)\n",
566
+ " trend = np.full(len(months), base + random.randint(-10, 10))\n",
567
+ "\n",
568
+ " seasonality = 10 * np.sin(np.linspace(0, 3 * np.pi, len(months)))\n",
569
+ " noise = np.random.normal(0, 5, len(months))\n",
570
+ " monthly_sales = np.clip(trend + seasonality + noise, a_min=0, a_max=None).astype(int)\n",
571
+ "\n",
572
+ " return list(zip(months.strftime(\"%Y-%m\"), monthly_sales))"
573
+ ]
574
+ },
575
+ {
576
+ "cell_type": "markdown",
577
+ "metadata": {
578
+ "id": "L2ak1HlcgoTe"
579
+ },
580
+ "source": [
581
+ "### *b. Run the function as part of building sales_data*"
582
+ ]
583
+ },
584
+ {
585
+ "cell_type": "code",
586
+ "execution_count": 15,
587
+ "metadata": {
588
+ "id": "SlJ24AUafoDB"
589
+ },
590
+ "outputs": [],
591
+ "source": [
592
+ "sales_data = []\n",
593
+ "for _, row in df_books.iterrows():\n",
594
+ " records = generate_sales_profile(row[\"sentiment_label\"])\n",
595
+ " for month, units in records:\n",
596
+ " sales_data.append({\n",
597
+ " \"title\": row[\"title\"],\n",
598
+ " \"month\": month,\n",
599
+ " \"units_sold\": units,\n",
600
+ " \"sentiment_label\": row[\"sentiment_label\"]\n",
601
+ " })"
602
+ ]
603
+ },
604
+ {
605
+ "cell_type": "markdown",
606
+ "metadata": {
607
+ "id": "4IXZKcCSgxnq"
608
+ },
609
+ "source": [
610
+ "### *c. ✋🏻🛑⛔️ Create a df_sales DataFrame from sales_data*\n",
611
+ "\n"
612
+ ]
613
+ },
614
+ {
615
+ "cell_type": "code",
616
+ "execution_count": 16,
617
+ "metadata": {
618
+ "id": "wcN6gtiZg-ws"
619
+ },
620
+ "outputs": [],
621
+ "source": [
622
+ "df_sales = pd.DataFrame(sales_data)"
623
+ ]
624
+ },
625
+ {
626
+ "cell_type": "markdown",
627
+ "metadata": {
628
+ "id": "EhIjz9WohAmZ"
629
+ },
630
+ "source": [
631
+ "### *d. Save df_sales as synthetic_sales_data.csv & view first few lines*"
632
+ ]
633
+ },
634
+ {
635
+ "cell_type": "code",
636
+ "execution_count": 17,
637
+ "metadata": {
638
+ "colab": {
639
+ "base_uri": "https://localhost:8080/"
640
+ },
641
+ "id": "MzbZvLcAhGaH",
642
+ "outputId": "3033960f-762f-4806-9016-09a610aa7f1b"
643
+ },
644
+ "outputs": [
645
+ {
646
+ "output_type": "stream",
647
+ "name": "stdout",
648
+ "text": [
649
+ " title month units_sold sentiment_label\n",
650
+ "0 A Light in the Attic 2024-09 100 neutral\n",
651
+ "1 A Light in the Attic 2024-10 109 neutral\n",
652
+ "2 A Light in the Attic 2024-11 102 neutral\n",
653
+ "3 A Light in the Attic 2024-12 107 neutral\n",
654
+ "4 A Light in the Attic 2025-01 108 neutral\n"
655
+ ]
656
+ }
657
+ ],
658
+ "source": [
659
+ "df_sales.to_csv(\"synthetic_sales_data.csv\", index=False)\n",
660
+ "\n",
661
+ "print(df_sales.head())"
662
+ ]
663
+ },
664
+ {
665
+ "cell_type": "markdown",
666
+ "metadata": {
667
+ "id": "7g9gqBgQMtJn"
668
+ },
669
+ "source": [
670
+ "## **5.** 🎯 Generate synthetic customer reviews"
671
+ ]
672
+ },
673
+ {
674
+ "cell_type": "markdown",
675
+ "metadata": {
676
+ "id": "Gi4y9M9KuDWx"
677
+ },
678
+ "source": [
679
+ "### *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*"
680
+ ]
681
+ },
682
+ {
683
+ "cell_type": "code",
684
+ "execution_count": 18,
685
+ "metadata": {
686
+ "id": "b3cd2a50"
687
+ },
688
+ "outputs": [],
689
+ "source": [
690
+ "synthetic_reviews_by_sentiment = {\n",
691
+ " \"positive\": [\n",
692
+ " \"A compelling and heartwarming read that stayed with me long after I finished.\",\n",
693
+ " \"Brilliantly written! The characters were unforgettable and the plot was engaging.\",\n",
694
+ " \"One of the best books I've read this year — inspiring and emotionally rich.\",\n",
695
+ " \"An absolute page-turner from start to finish.\",\n",
696
+ " \"The storytelling was captivating and beautifully crafted.\",\n",
697
+ " \"I couldn't put it down; every chapter pulled me in deeper.\",\n",
698
+ " \"A masterfully told story with vivid and memorable characters.\",\n",
699
+ " \"Emotionally powerful and wonderfully executed.\",\n",
700
+ " \"The author’s writing style is elegant and immersive.\",\n",
701
+ " \"A truly uplifting and satisfying read.\",\n",
702
+ " \"This book exceeded all my expectations.\",\n",
703
+ " \"Rich in detail and full of heart.\",\n",
704
+ " \"An inspiring story that left me feeling hopeful.\",\n",
705
+ " \"The pacing was perfect and kept me engaged throughout.\",\n",
706
+ " \"A fantastic journey that I didn’t want to end.\",\n",
707
+ " \"Thought-provoking and deeply moving.\",\n",
708
+ " \"A beautifully imagined world with compelling themes.\",\n",
709
+ " \"The dialogue felt natural and authentic.\",\n",
710
+ " \"An unforgettable literary experience.\",\n",
711
+ " \"Creative, original, and wonderfully written.\",\n",
712
+ " \"The characters felt real and relatable.\",\n",
713
+ " \"An engaging plot with satisfying twists.\",\n",
714
+ " \"I was hooked from the very first page.\",\n",
715
+ " \"A powerful narrative that resonated with me.\",\n",
716
+ " \"Smart, insightful, and emotionally rich.\",\n",
717
+ " \"An entertaining and meaningful story.\",\n",
718
+ " \"The writing was polished and full of depth.\",\n",
719
+ " \"A refreshing and unique perspective.\",\n",
720
+ " \"The emotional impact of this book was incredible.\",\n",
721
+ " \"A must-read for fans of the genre.\",\n",
722
+ " \"It balanced humor and heart perfectly.\",\n",
723
+ " \"A gripping story that kept me invested.\",\n",
724
+ " \"The themes were explored thoughtfully and effectively.\",\n",
725
+ " \"An excellent blend of action and character development.\",\n",
726
+ " \"A deeply satisfying conclusion to a great story.\",\n",
727
+ " \"Beautiful prose paired with a compelling storyline.\",\n",
728
+ " \"It left me thinking about it for days.\",\n",
729
+ " \"An inspiring tale of resilience and growth.\",\n",
730
+ " \"The atmosphere was vivid and immersive.\",\n",
731
+ " \"A rewarding and memorable reading experience.\",\n",
732
+ " \"The author created a world I completely believed in.\",\n",
733
+ " \"Every chapter added something meaningful.\",\n",
734
+ " \"A story told with passion and precision.\",\n",
735
+ " \"Truly a standout book in its category.\",\n",
736
+ " \"An emotionally satisfying and engaging read.\",\n",
737
+ " \"The plot twists were surprising yet believable.\",\n",
738
+ " \"A wonderfully crafted and enjoyable novel.\",\n",
739
+ " \"It struck the perfect balance between drama and warmth.\",\n",
740
+ " \"An outstanding work of storytelling.\",\n",
741
+ " \"A delightful and enriching book overall.\"\n",
742
+ " ],\n",
743
+ " \"neutral\": [\n",
744
+ " \"An average book — not great, but not bad either.\",\n",
745
+ " \"Some parts really stood out, others felt a bit flat.\",\n",
746
+ " \"It was okay overall. A decent way to pass the time.\",\n",
747
+ " \"A fairly standard story without many surprises.\",\n",
748
+ " \"The writing was fine, though not particularly memorable.\",\n",
749
+ " \"An easy read, but nothing especially remarkable.\",\n",
750
+ " \"It had its moments, though it didn’t fully captivate me.\",\n",
751
+ " \"The characters were decent but not very memorable.\",\n",
752
+ " \"A straightforward plot that delivered what it promised.\",\n",
753
+ " \"Not my favorite, but not disappointing either.\",\n",
754
+ " \"The pacing was uneven in places.\",\n",
755
+ " \"An enjoyable enough read, though somewhat predictable.\",\n",
756
+ " \"It was mildly interesting but lacked depth.\",\n",
757
+ " \"A simple story told competently.\",\n",
758
+ " \"Some chapters were engaging, others less so.\",\n",
759
+ " \"A solid effort, though it didn’t stand out.\",\n",
760
+ " \"It met my expectations, but didn’t exceed them.\",\n",
761
+ " \"The themes were clear but not deeply explored.\",\n",
762
+ " \"An adequate book for a quiet afternoon.\",\n",
763
+ " \"The storyline was easy to follow but fairly conventional.\",\n",
764
+ " \"There were interesting ideas, though not fully developed.\",\n",
765
+ " \"The writing style was straightforward and clear.\",\n",
766
+ " \"A mixed experience with highs and lows.\",\n",
767
+ " \"It started strong but lost momentum midway.\",\n",
768
+ " \"An acceptable read with room for improvement.\",\n",
769
+ " \"The ending was satisfactory but not surprising.\",\n",
770
+ " \"Some aspects worked better than others.\",\n",
771
+ " \"A predictable but readable story.\",\n",
772
+ " \"It held my attention, though not consistently.\",\n",
773
+ " \"The characters were serviceable for the plot.\",\n",
774
+ " \"An average addition to the genre.\",\n",
775
+ " \"It had potential that wasn’t fully realized.\",\n",
776
+ " \"The book was competently written.\",\n",
777
+ " \"A neutral reading experience overall.\",\n",
778
+ " \"Not particularly engaging, but not dull either.\",\n",
779
+ " \"It delivered a standard narrative arc.\",\n",
780
+ " \"Some emotional moments, though not deeply impactful.\",\n",
781
+ " \"The setting was interesting but underused.\",\n",
782
+ " \"An easy but forgettable read.\",\n",
783
+ " \"It was fine, though I likely won’t revisit it.\",\n",
784
+ " \"The dialogue was functional but unremarkable.\",\n",
785
+ " \"A moderately entertaining story.\",\n",
786
+ " \"It felt balanced but lacked excitement.\",\n",
787
+ " \"The book maintained a steady tone throughout.\",\n",
788
+ " \"Neither impressive nor disappointing.\",\n",
789
+ " \"A passable story with conventional elements.\",\n",
790
+ " \"It did what it set out to do.\",\n",
791
+ " \"A readable book without strong highs or lows.\",\n",
792
+ " \"The plot moved along at a reasonable pace.\",\n",
793
+ " \"Overall, a fairly ordinary reading experience.\"\n",
794
+ " ],\n",
795
+ " \"negative\": [\n",
796
+ " \"I struggled to get through this one — it just didn’t grab me.\",\n",
797
+ " \"The plot was confusing and the characters felt underdeveloped.\",\n",
798
+ " \"Disappointing. I had high hopes, but they weren't met.\",\n",
799
+ " \"The pacing was painfully slow and unfocused.\",\n",
800
+ " \"I found the story dull and unengaging.\",\n",
801
+ " \"The writing felt flat and uninspired.\",\n",
802
+ " \"The characters lacked depth and realism.\",\n",
803
+ " \"A forgettable and frustrating read.\",\n",
804
+ " \"The dialogue felt awkward and forced.\",\n",
805
+ " \"It failed to hold my interest.\",\n",
806
+ " \"The story seemed disorganized and messy.\",\n",
807
+ " \"I couldn’t connect with any of the characters.\",\n",
808
+ " \"The ending was unsatisfying and abrupt.\",\n",
809
+ " \"The book felt much longer than it needed to be.\",\n",
810
+ " \"A predictable plot with no real surprises.\",\n",
811
+ " \"The themes were shallow and poorly executed.\",\n",
812
+ " \"I found myself skimming just to finish it.\",\n",
813
+ " \"The narrative lacked clarity and focus.\",\n",
814
+ " \"An underwhelming and disappointing experience.\",\n",
815
+ " \"The story never really came together.\",\n",
816
+ " \"It started poorly and never improved.\",\n",
817
+ " \"The writing style didn’t appeal to me at all.\",\n",
818
+ " \"A tedious read from beginning to end.\",\n",
819
+ " \"The characters’ motivations felt unclear.\",\n",
820
+ " \"It lacked originality and creativity.\",\n",
821
+ " \"The plot twists felt forced and unrealistic.\",\n",
822
+ " \"I expected much more from this author.\",\n",
823
+ " \"The book felt rushed and incomplete.\",\n",
824
+ " \"A bland story with little emotional impact.\",\n",
825
+ " \"The world-building was weak and inconsistent.\",\n",
826
+ " \"I regret spending time on this book.\",\n",
827
+ " \"The storyline was repetitive and dull.\",\n",
828
+ " \"It failed to deliver on its premise.\",\n",
829
+ " \"The tone felt inconsistent and confusing.\",\n",
830
+ " \"The book was difficult to stay engaged with.\",\n",
831
+ " \"The emotional moments felt unearned.\",\n",
832
+ " \"A frustratingly uneven narrative.\",\n",
833
+ " \"The characters made unrealistic decisions.\",\n",
834
+ " \"It didn’t live up to the hype.\",\n",
835
+ " \"The writing felt overly simplistic.\",\n",
836
+ " \"The book lacked tension and excitement.\",\n",
837
+ " \"A poorly executed concept.\",\n",
838
+ " \"The pacing dragged throughout.\",\n",
839
+ " \"I found it more irritating than enjoyable.\",\n",
840
+ " \"The plot holes were distracting.\",\n",
841
+ " \"An unsatisfying and forgettable novel.\",\n",
842
+ " \"The storytelling felt amateurish.\",\n",
843
+ " \"It never fully developed its ideas.\",\n",
844
+ " \"A disappointing addition to the genre.\",\n",
845
+ " \"Overall, not a book I would recommend.\"\n",
846
+ " ]\n",
847
+ "}"
848
+ ]
849
+ },
850
+ {
851
+ "cell_type": "markdown",
852
+ "metadata": {
853
+ "id": "fQhfVaDmuULT"
854
+ },
855
+ "source": [
856
+ "### *b. Generate 10 reviews per book using random sampling from the corresponding 50*"
857
+ ]
858
+ },
859
+ {
860
+ "cell_type": "code",
861
+ "execution_count": 19,
862
+ "metadata": {
863
+ "id": "l2SRc3PjuTGM"
864
+ },
865
+ "outputs": [],
866
+ "source": [
867
+ "review_rows = []\n",
868
+ "for _, row in df_books.iterrows():\n",
869
+ " title = row['title']\n",
870
+ " sentiment_label = row['sentiment_label']\n",
871
+ " review_pool = synthetic_reviews_by_sentiment[sentiment_label]\n",
872
+ " sampled_reviews = random.sample(review_pool, 10)\n",
873
+ " for review_text in sampled_reviews:\n",
874
+ " review_rows.append({\n",
875
+ " \"title\": title,\n",
876
+ " \"sentiment_label\": sentiment_label,\n",
877
+ " \"review_text\": review_text,\n",
878
+ " \"rating\": row['rating'],\n",
879
+ " \"popularity_score\": row['popularity_score']\n",
880
+ " })"
881
+ ]
882
+ },
883
+ {
884
+ "cell_type": "markdown",
885
+ "metadata": {
886
+ "id": "bmJMXF-Bukdm"
887
+ },
888
+ "source": [
889
+ "### *c. Create the final dataframe df_reviews & save it as synthetic_book_reviews.csv*"
890
+ ]
891
+ },
892
+ {
893
+ "cell_type": "code",
894
+ "execution_count": 20,
895
+ "metadata": {
896
+ "id": "ZUKUqZsuumsp"
897
+ },
898
+ "outputs": [],
899
+ "source": [
900
+ "df_reviews = pd.DataFrame(review_rows)\n",
901
+ "df_reviews.to_csv(\"synthetic_book_reviews.csv\", index=False)"
902
+ ]
903
+ },
904
+ {
905
+ "cell_type": "markdown",
906
+ "source": [
907
+ "### *c. inputs for R*"
908
+ ],
909
+ "metadata": {
910
+ "id": "_602pYUS3gY5"
911
+ }
912
+ },
913
+ {
914
+ "cell_type": "code",
915
+ "execution_count": 21,
916
+ "metadata": {
917
+ "colab": {
918
+ "base_uri": "https://localhost:8080/"
919
+ },
920
+ "id": "3946e521",
921
+ "outputId": "cdf0109a-0720-4a51-9882-77712bb22e9d"
922
+ },
923
+ "outputs": [
924
+ {
925
+ "output_type": "stream",
926
+ "name": "stdout",
927
+ "text": [
928
+ "✅ Wrote synthetic_title_level_features.csv\n",
929
+ "✅ Wrote synthetic_monthly_revenue_series.csv\n"
930
+ ]
931
+ }
932
+ ],
933
+ "source": [
934
+ "import numpy as np\n",
935
+ "\n",
936
+ "def _safe_num(s):\n",
937
+ " return pd.to_numeric(\n",
938
+ " pd.Series(s).astype(str).str.replace(r\"[^0-9.]\", \"\", regex=True),\n",
939
+ " errors=\"coerce\"\n",
940
+ " )\n",
941
+ "\n",
942
+ "# --- Clean book metadata (price/rating) ---\n",
943
+ "df_books_r = df_books.copy()\n",
944
+ "if \"price\" in df_books_r.columns:\n",
945
+ " df_books_r[\"price\"] = _safe_num(df_books_r[\"price\"])\n",
946
+ "if \"rating\" in df_books_r.columns:\n",
947
+ " df_books_r[\"rating\"] = _safe_num(df_books_r[\"rating\"])\n",
948
+ "\n",
949
+ "df_books_r[\"title\"] = df_books_r[\"title\"].astype(str).str.strip()\n",
950
+ "\n",
951
+ "# --- Clean sales ---\n",
952
+ "df_sales_r = df_sales.copy()\n",
953
+ "df_sales_r[\"title\"] = df_sales_r[\"title\"].astype(str).str.strip()\n",
954
+ "df_sales_r[\"month\"] = pd.to_datetime(df_sales_r[\"month\"], errors=\"coerce\")\n",
955
+ "df_sales_r[\"units_sold\"] = _safe_num(df_sales_r[\"units_sold\"])\n",
956
+ "\n",
957
+ "# --- Clean reviews ---\n",
958
+ "df_reviews_r = df_reviews.copy()\n",
959
+ "df_reviews_r[\"title\"] = df_reviews_r[\"title\"].astype(str).str.strip()\n",
960
+ "df_reviews_r[\"sentiment_label\"] = df_reviews_r[\"sentiment_label\"].astype(str).str.lower().str.strip()\n",
961
+ "if \"rating\" in df_reviews_r.columns:\n",
962
+ " df_reviews_r[\"rating\"] = _safe_num(df_reviews_r[\"rating\"])\n",
963
+ "if \"popularity_score\" in df_reviews_r.columns:\n",
964
+ " df_reviews_r[\"popularity_score\"] = _safe_num(df_reviews_r[\"popularity_score\"])\n",
965
+ "\n",
966
+ "# --- Sentiment shares per title (from reviews) ---\n",
967
+ "sent_counts = (\n",
968
+ " df_reviews_r.groupby([\"title\", \"sentiment_label\"])\n",
969
+ " .size()\n",
970
+ " .unstack(fill_value=0)\n",
971
+ ")\n",
972
+ "for lab in [\"positive\", \"neutral\", \"negative\"]:\n",
973
+ " if lab not in sent_counts.columns:\n",
974
+ " sent_counts[lab] = 0\n",
975
+ "\n",
976
+ "sent_counts[\"total_reviews\"] = sent_counts[[\"positive\", \"neutral\", \"negative\"]].sum(axis=1)\n",
977
+ "den = sent_counts[\"total_reviews\"].replace(0, np.nan)\n",
978
+ "sent_counts[\"share_positive\"] = sent_counts[\"positive\"] / den\n",
979
+ "sent_counts[\"share_neutral\"] = sent_counts[\"neutral\"] / den\n",
980
+ "sent_counts[\"share_negative\"] = sent_counts[\"negative\"] / den\n",
981
+ "sent_counts = sent_counts.reset_index()\n",
982
+ "\n",
983
+ "# --- Sales aggregation per title ---\n",
984
+ "sales_by_title = (\n",
985
+ " df_sales_r.dropna(subset=[\"title\"])\n",
986
+ " .groupby(\"title\", as_index=False)\n",
987
+ " .agg(\n",
988
+ " months_observed=(\"month\", \"nunique\"),\n",
989
+ " avg_units_sold=(\"units_sold\", \"mean\"),\n",
990
+ " total_units_sold=(\"units_sold\", \"sum\"),\n",
991
+ " )\n",
992
+ ")\n",
993
+ "\n",
994
+ "# --- Title-level features (join sales + books + sentiment) ---\n",
995
+ "df_title = (\n",
996
+ " sales_by_title\n",
997
+ " .merge(df_books_r[[\"title\", \"price\", \"rating\"]], on=\"title\", how=\"left\")\n",
998
+ " .merge(sent_counts[[\"title\", \"share_positive\", \"share_neutral\", \"share_negative\", \"total_reviews\"]],\n",
999
+ " on=\"title\", how=\"left\")\n",
1000
+ ")\n",
1001
+ "\n",
1002
+ "df_title[\"avg_revenue\"] = df_title[\"avg_units_sold\"] * df_title[\"price\"]\n",
1003
+ "df_title[\"total_revenue\"] = df_title[\"total_units_sold\"] * df_title[\"price\"]\n",
1004
+ "\n",
1005
+ "df_title.to_csv(\"synthetic_title_level_features.csv\", index=False)\n",
1006
+ "print(\"✅ Wrote synthetic_title_level_features.csv\")\n",
1007
+ "\n",
1008
+ "# --- Monthly revenue series (proxy: units_sold * price) ---\n",
1009
+ "monthly_rev = (\n",
1010
+ " df_sales_r.merge(df_books_r[[\"title\", \"price\"]], on=\"title\", how=\"left\")\n",
1011
+ ")\n",
1012
+ "monthly_rev[\"revenue\"] = monthly_rev[\"units_sold\"] * monthly_rev[\"price\"]\n",
1013
+ "\n",
1014
+ "df_monthly = (\n",
1015
+ " monthly_rev.dropna(subset=[\"month\"])\n",
1016
+ " .groupby(\"month\", as_index=False)[\"revenue\"]\n",
1017
+ " .sum()\n",
1018
+ " .rename(columns={\"revenue\": \"total_revenue\"})\n",
1019
+ " .sort_values(\"month\")\n",
1020
+ ")\n",
1021
+ "# if revenue is all NA (e.g., missing price), fallback to units_sold as a teaching proxy\n",
1022
+ "if df_monthly[\"total_revenue\"].notna().sum() == 0:\n",
1023
+ " df_monthly = (\n",
1024
+ " df_sales_r.dropna(subset=[\"month\"])\n",
1025
+ " .groupby(\"month\", as_index=False)[\"units_sold\"]\n",
1026
+ " .sum()\n",
1027
+ " .rename(columns={\"units_sold\": \"total_revenue\"})\n",
1028
+ " .sort_values(\"month\")\n",
1029
+ " )\n",
1030
+ "\n",
1031
+ "df_monthly[\"month\"] = pd.to_datetime(df_monthly[\"month\"], errors=\"coerce\").dt.strftime(\"%Y-%m-%d\")\n",
1032
+ "df_monthly.to_csv(\"synthetic_monthly_revenue_series.csv\", index=False)\n",
1033
+ "print(\"✅ Wrote synthetic_monthly_revenue_series.csv\")\n"
1034
+ ]
1035
+ },
1036
+ {
1037
+ "cell_type": "markdown",
1038
+ "metadata": {
1039
+ "id": "RYvGyVfXuo54"
1040
+ },
1041
+ "source": [
1042
+ "### *d. ✋🏻🛑⛔️ View the first few lines*"
1043
+ ]
1044
+ },
1045
+ {
1046
+ "cell_type": "markdown",
1047
+ "source": [
1048
+ "**Last part to complete**"
1049
+ ],
1050
+ "metadata": {
1051
+ "id": "6Ub_snNWKra_"
1052
+ }
1053
+ },
1054
+ {
1055
+ "cell_type": "code",
1056
+ "source": [
1057
+ "display(df_books.head())"
1058
+ ],
1059
+ "metadata": {
1060
+ "colab": {
1061
+ "base_uri": "https://localhost:8080/",
1062
+ "height": 206
1063
+ },
1064
+ "id": "3yDzBL_S3AOw",
1065
+ "outputId": "34c6963f-0e45-40e7-c58c-af480f43556b"
1066
+ },
1067
+ "execution_count": 22,
1068
+ "outputs": [
1069
+ {
1070
+ "output_type": "display_data",
1071
+ "data": {
1072
+ "text/plain": [
1073
+ " title price rating popularity_score \\\n",
1074
+ "0 A Light in the Attic 51.77 Three 3 \n",
1075
+ "1 Tipping the Velvet 53.74 One 2 \n",
1076
+ "2 Soumission 50.10 One 2 \n",
1077
+ "3 Sharp Objects 47.82 Four 4 \n",
1078
+ "4 Sapiens: A Brief History of Humankind 54.23 Five 3 \n",
1079
+ "\n",
1080
+ " sentiment_label \n",
1081
+ "0 neutral \n",
1082
+ "1 negative \n",
1083
+ "2 negative \n",
1084
+ "3 positive \n",
1085
+ "4 neutral "
1086
+ ],
1087
+ "text/html": [
1088
+ "\n",
1089
+ " <div id=\"df-37551206-2c1b-41a7-b409-da6a6e900bae\" class=\"colab-df-container\">\n",
1090
+ " <div>\n",
1091
+ "<style scoped>\n",
1092
+ " .dataframe tbody tr th:only-of-type {\n",
1093
+ " vertical-align: middle;\n",
1094
+ " }\n",
1095
+ "\n",
1096
+ " .dataframe tbody tr th {\n",
1097
+ " vertical-align: top;\n",
1098
+ " }\n",
1099
+ "\n",
1100
+ " .dataframe thead th {\n",
1101
+ " text-align: right;\n",
1102
+ " }\n",
1103
+ "</style>\n",
1104
+ "<table border=\"1\" class=\"dataframe\">\n",
1105
+ " <thead>\n",
1106
+ " <tr style=\"text-align: right;\">\n",
1107
+ " <th></th>\n",
1108
+ " <th>title</th>\n",
1109
+ " <th>price</th>\n",
1110
+ " <th>rating</th>\n",
1111
+ " <th>popularity_score</th>\n",
1112
+ " <th>sentiment_label</th>\n",
1113
+ " </tr>\n",
1114
+ " </thead>\n",
1115
+ " <tbody>\n",
1116
+ " <tr>\n",
1117
+ " <th>0</th>\n",
1118
+ " <td>A Light in the Attic</td>\n",
1119
+ " <td>51.77</td>\n",
1120
+ " <td>Three</td>\n",
1121
+ " <td>3</td>\n",
1122
+ " <td>neutral</td>\n",
1123
+ " </tr>\n",
1124
+ " <tr>\n",
1125
+ " <th>1</th>\n",
1126
+ " <td>Tipping the Velvet</td>\n",
1127
+ " <td>53.74</td>\n",
1128
+ " <td>One</td>\n",
1129
+ " <td>2</td>\n",
1130
+ " <td>negative</td>\n",
1131
+ " </tr>\n",
1132
+ " <tr>\n",
1133
+ " <th>2</th>\n",
1134
+ " <td>Soumission</td>\n",
1135
+ " <td>50.10</td>\n",
1136
+ " <td>One</td>\n",
1137
+ " <td>2</td>\n",
1138
+ " <td>negative</td>\n",
1139
+ " </tr>\n",
1140
+ " <tr>\n",
1141
+ " <th>3</th>\n",
1142
+ " <td>Sharp Objects</td>\n",
1143
+ " <td>47.82</td>\n",
1144
+ " <td>Four</td>\n",
1145
+ " <td>4</td>\n",
1146
+ " <td>positive</td>\n",
1147
+ " </tr>\n",
1148
+ " <tr>\n",
1149
+ " <th>4</th>\n",
1150
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
1151
+ " <td>54.23</td>\n",
1152
+ " <td>Five</td>\n",
1153
+ " <td>3</td>\n",
1154
+ " <td>neutral</td>\n",
1155
+ " </tr>\n",
1156
+ " </tbody>\n",
1157
+ "</table>\n",
1158
+ "</div>\n",
1159
+ " <div class=\"colab-df-buttons\">\n",
1160
+ "\n",
1161
+ " <div class=\"colab-df-container\">\n",
1162
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-37551206-2c1b-41a7-b409-da6a6e900bae')\"\n",
1163
+ " title=\"Convert this dataframe to an interactive table.\"\n",
1164
+ " style=\"display:none;\">\n",
1165
+ "\n",
1166
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
1167
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
1168
+ " </svg>\n",
1169
+ " </button>\n",
1170
+ "\n",
1171
+ " <style>\n",
1172
+ " .colab-df-container {\n",
1173
+ " display:flex;\n",
1174
+ " gap: 12px;\n",
1175
+ " }\n",
1176
+ "\n",
1177
+ " .colab-df-convert {\n",
1178
+ " background-color: #E8F0FE;\n",
1179
+ " border: none;\n",
1180
+ " border-radius: 50%;\n",
1181
+ " cursor: pointer;\n",
1182
+ " display: none;\n",
1183
+ " fill: #1967D2;\n",
1184
+ " height: 32px;\n",
1185
+ " padding: 0 0 0 0;\n",
1186
+ " width: 32px;\n",
1187
+ " }\n",
1188
+ "\n",
1189
+ " .colab-df-convert:hover {\n",
1190
+ " background-color: #E2EBFA;\n",
1191
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
1192
+ " fill: #174EA6;\n",
1193
+ " }\n",
1194
+ "\n",
1195
+ " .colab-df-buttons div {\n",
1196
+ " margin-bottom: 4px;\n",
1197
+ " }\n",
1198
+ "\n",
1199
+ " [theme=dark] .colab-df-convert {\n",
1200
+ " background-color: #3B4455;\n",
1201
+ " fill: #D2E3FC;\n",
1202
+ " }\n",
1203
+ "\n",
1204
+ " [theme=dark] .colab-df-convert:hover {\n",
1205
+ " background-color: #434B5C;\n",
1206
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
1207
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
1208
+ " fill: #FFFFFF;\n",
1209
+ " }\n",
1210
+ " </style>\n",
1211
+ "\n",
1212
+ " <script>\n",
1213
+ " const buttonEl =\n",
1214
+ " document.querySelector('#df-37551206-2c1b-41a7-b409-da6a6e900bae button.colab-df-convert');\n",
1215
+ " buttonEl.style.display =\n",
1216
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
1217
+ "\n",
1218
+ " async function convertToInteractive(key) {\n",
1219
+ " const element = document.querySelector('#df-37551206-2c1b-41a7-b409-da6a6e900bae');\n",
1220
+ " const dataTable =\n",
1221
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
1222
+ " [key], {});\n",
1223
+ " if (!dataTable) return;\n",
1224
+ "\n",
1225
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
1226
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
1227
+ " + ' to learn more about interactive tables.';\n",
1228
+ " element.innerHTML = '';\n",
1229
+ " dataTable['output_type'] = 'display_data';\n",
1230
+ " await google.colab.output.renderOutput(dataTable, element);\n",
1231
+ " const docLink = document.createElement('div');\n",
1232
+ " docLink.innerHTML = docLinkHtml;\n",
1233
+ " element.appendChild(docLink);\n",
1234
+ " }\n",
1235
+ " </script>\n",
1236
+ " </div>\n",
1237
+ "\n",
1238
+ "\n",
1239
+ " </div>\n",
1240
+ " </div>\n"
1241
+ ],
1242
+ "application/vnd.google.colaboratory.intrinsic+json": {
1243
+ "type": "dataframe",
1244
+ "summary": "{\n \"name\": \"display(df_books\",\n \"rows\": 5,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"Tipping the Velvet\",\n \"Sapiens: A Brief History of Humankind\",\n \"Soumission\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"price\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2.647672562837028,\n \"min\": 47.82,\n \"max\": 54.23,\n \"num_unique_values\": 5,\n \"samples\": [\n 53.74,\n 54.23,\n 50.1\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 4,\n \"samples\": [\n \"One\",\n \"Five\",\n \"Three\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"popularity_score\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 2,\n \"max\": 4,\n \"num_unique_values\": 3,\n \"samples\": [\n 3,\n 2,\n 4\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"sentiment_label\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"neutral\",\n \"negative\",\n \"positive\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
1245
+ }
1246
+ },
1247
+ "metadata": {}
1248
+ }
1249
+ ]
1250
+ }
1251
+ ],
1252
+ "metadata": {
1253
+ "colab": {
1254
+ "collapsed_sections": [
1255
+ "jpASMyIQMaAq",
1256
+ "lquNYCbfL9IM",
1257
+ "0IWuNpxxYDJF",
1258
+ "oCdTsin2Yfp3",
1259
+ "T0TOeRC4Yrnn",
1260
+ "duI5dv3CZYvF",
1261
+ "qMjRKMBQZlJi",
1262
+ "p-1Pr2szaqLk",
1263
+ "SIaJUGIpaH4V",
1264
+ "pY4yCoIuaQqp",
1265
+ "n4-TaNTFgPak",
1266
+ "HnngRNTgacYt",
1267
+ "HF9F9HIzgT7Z",
1268
+ "T8AdKkmASq9a",
1269
+ "OhXbdGD5fH0c",
1270
+ "L2ak1HlcgoTe",
1271
+ "4IXZKcCSgxnq",
1272
+ "EhIjz9WohAmZ",
1273
+ "Gi4y9M9KuDWx",
1274
+ "fQhfVaDmuULT",
1275
+ "bmJMXF-Bukdm",
1276
+ "RYvGyVfXuo54"
1277
+ ],
1278
+ "provenance": []
1279
+ },
1280
+ "kernelspec": {
1281
+ "display_name": "Python 3",
1282
+ "name": "python3"
1283
+ },
1284
+ "language_info": {
1285
+ "name": "python"
1286
+ }
1287
+ },
1288
+ "nbformat": 4,
1289
+ "nbformat_minor": 0
1290
+ }
2a_Python_Analysis_Phileas_Mazeyrie__Rosset_Seminar_F.ipynb ADDED
The diff for this file is too large to render. See raw diff