pandas-pd-pcg 0.0.0-stage → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +11 -4
- package/pandas-t/pandas-ex/All_Practical_Solutions_Combined.docx +0 -0
- package/pandas-t/pandas-ex/RPA_Journal_Solutions.pdf +0 -0
- package/pandas-t/pandas-ex/threadora_simple.pdf +0 -0
- package/pandas-t/pandas-ex/threadora_simple.py +520 -0
- package/pandas-t/pandas-jnl/AIOP_Practical_Journal.pdf +0 -0
- package/pandas-t/pandas-jnl/BDH.pdf +0 -0
- package/pandas-t/pandas-jnl/DIV.pdf +0 -0
- package/pandas-t/pandas-jnl/ML_Fundamentals_Journal.pdf +0 -0
- package/pandas-t/pandas-jnl/RPA_Journal.pdf +0 -0
- package/pandas-t/pd/2r.txt +95 -0
- package/pandas-t/pd/3m/q1_preprocessing.py +78 -0
- package/pandas-t/pd/3m/q2_eda.py +61 -0
- package/pandas-t/pd/3m/q3_simple_linear_regression.py +85 -0
- package/pandas-t/pd/3m/q4_logistic_regression.py +92 -0
- package/pandas-t/pd/3m/q5_full_exam_pipeline.py +118 -0
- package/pandas-t/pd/4a/1_BFS.py +32 -0
- package/pandas-t/pd/4a/2_DFS.py +31 -0
- package/pandas-t/pd/4a/4_A_Star_NetworkX.py +17 -0
- package/pandas-t/pd/4a/5_Rule_Based_Chatbot.py +34 -0
- package/pandas-t/pd/5b/ATCalc/ATCalc.java +32 -0
- package/pandas-t/pd/5b/ATCalc/ATMapper.java +27 -0
- package/pandas-t/pd/5b/ATCalc/ATReducer.java +27 -0
- package/pandas-t/pd/5b/ATCalc/MRC.txt +14 -0
- package/pandas-t/pd/5b/Hive/H_CRUD.txt +129 -0
- package/pandas-t/pd/5b/Hive/H_Query.txt +36 -0
- package/pandas-t/pd/5b/Hive/Startingservices.txt +9 -0
- package/pandas-t/pd/5b/M.txt +32 -0
- package/pandas-t/pd/d1/1d.txt +85 -0
- package/pandas-t/pd/d1/q1_data_acquisition_and_cleaning.py +65 -0
- package/pandas-t/pd/d1/q2_encoding_and_scaling.py +70 -0
- package/pandas-t/pd/d1/q3_eda_summary_outliers_correlation.py +77 -0
- package/pandas-t/pd/d1/q4_data_visualization.py +123 -0
- package/pandas-t/pd/d1/q5_linear_regression_sales.py +75 -0
- package/pandas-t/pd/d1/q6_logistic_regression_high_sales.py +71 -0
- package/pandas-t/pd/d1/q7_weekly_pattern_and_business_insights.py +89 -0
- package/pandas-t/pd/d1/q8_full_journal_pipeline.py +115 -0
- package/pandas-t/pd/d1/questions_bank.md +49 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pandas-pd-pcg",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.2",
|
|
4
|
+
"description": "pandas-pd-pcg package",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"type": "commonjs",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
9
|
+
},
|
|
10
|
+
"keywords": [],
|
|
11
|
+
"author": "",
|
|
12
|
+
"license": "ISC"
|
|
13
|
+
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
"""
|
|
2
|
+
THREADORA BOUTIQUE - SIMPLE ML PRACTICAL
|
|
3
|
+
=========================================
|
|
4
|
+
This is a beginner-friendly version of the Threadora Boutique analysis.
|
|
5
|
+
It does the same steps as the original file, but the code is written in
|
|
6
|
+
small, simple pieces with clear comments, so it is easy to read and follow.
|
|
7
|
+
|
|
8
|
+
Put "threadora_boutique_data.csv" in the same folder as this file before
|
|
9
|
+
running it.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import pandas as pd
|
|
14
|
+
import numpy as np
|
|
15
|
+
import matplotlib.pyplot as plt
|
|
16
|
+
import seaborn as sns
|
|
17
|
+
from sklearn.model_selection import train_test_split
|
|
18
|
+
from sklearn.linear_model import LinearRegression, LogisticRegression
|
|
19
|
+
from sklearn.preprocessing import MinMaxScaler, StandardScaler
|
|
20
|
+
from sklearn.metrics import (
|
|
21
|
+
mean_absolute_error, mean_squared_error, r2_score,
|
|
22
|
+
accuracy_score, precision_score, recall_score,
|
|
23
|
+
confusion_matrix, classification_report
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# -------------------------------------------------------------------
|
|
27
|
+
# SETTINGS
|
|
28
|
+
# -------------------------------------------------------------------
|
|
29
|
+
CSV_FILE = "threadora_boutique_data.csv"
|
|
30
|
+
OUTPUT_FOLDER = "threadora_outputs"
|
|
31
|
+
NUMBER_COLUMNS = ["Footfall", "Sales", "Ad_Spend", "Insta_Mentions", "Whatsapp_Inquiries"]
|
|
32
|
+
CATEGORY_COLUMNS = ["Day", "Deal_Offered"]
|
|
33
|
+
FEATURE_COLUMNS = ["Ad_Spend", "Footfall", "Whatsapp_Inquiries", "Insta_Mentions"]
|
|
34
|
+
DAY_ORDER = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
|
|
35
|
+
|
|
36
|
+
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
|
|
37
|
+
sns.set_theme(style="whitegrid")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def save_and_show_plot(file_name):
|
|
41
|
+
"""Save the current plot to the output folder and display it."""
|
|
42
|
+
plt.tight_layout()
|
|
43
|
+
plt.savefig(f"{OUTPUT_FOLDER}/{file_name}", dpi=150)
|
|
44
|
+
plt.show()
|
|
45
|
+
plt.close()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# -------------------------------------------------------------------
|
|
49
|
+
# STEP 1: LOAD THE DATA
|
|
50
|
+
# -------------------------------------------------------------------
|
|
51
|
+
def load_data():
|
|
52
|
+
print("\n" + "=" * 70)
|
|
53
|
+
print("STEP 1: LOAD THE DATA")
|
|
54
|
+
print("=" * 70)
|
|
55
|
+
|
|
56
|
+
data = pd.read_csv(CSV_FILE)
|
|
57
|
+
print(data.head())
|
|
58
|
+
print("\nShape:", data.shape)
|
|
59
|
+
print("\nColumns:", list(data.columns))
|
|
60
|
+
|
|
61
|
+
return data
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# -------------------------------------------------------------------
|
|
65
|
+
# STEP 2: CLEAN THE DATA
|
|
66
|
+
# -------------------------------------------------------------------
|
|
67
|
+
def clean_data(data):
|
|
68
|
+
print("\n" + "=" * 70)
|
|
69
|
+
print("STEP 2: CLEAN THE DATA")
|
|
70
|
+
print("=" * 70)
|
|
71
|
+
|
|
72
|
+
print("\nMissing values before cleaning:")
|
|
73
|
+
print(data.isnull().sum())
|
|
74
|
+
print("\nDuplicate rows:", data.duplicated().sum())
|
|
75
|
+
|
|
76
|
+
# Make sure number columns really contain numbers
|
|
77
|
+
for column in NUMBER_COLUMNS:
|
|
78
|
+
data[column] = pd.to_numeric(data[column], errors="coerce")
|
|
79
|
+
|
|
80
|
+
# Fill missing numbers with the median of that column
|
|
81
|
+
for column in NUMBER_COLUMNS:
|
|
82
|
+
data[column] = data[column].fillna(data[column].median())
|
|
83
|
+
|
|
84
|
+
# Fill missing categories with the most common value
|
|
85
|
+
for column in CATEGORY_COLUMNS:
|
|
86
|
+
data[column] = data[column].fillna(data[column].mode()[0])
|
|
87
|
+
|
|
88
|
+
# Fix the date column
|
|
89
|
+
data["Date"] = pd.to_datetime(data["Date"], errors="coerce").ffill().bfill()
|
|
90
|
+
|
|
91
|
+
# Remove duplicate rows
|
|
92
|
+
rows_before = len(data)
|
|
93
|
+
data = data.drop_duplicates().copy()
|
|
94
|
+
print("\nDuplicate rows removed:", rows_before - len(data))
|
|
95
|
+
|
|
96
|
+
# Turn "Yes"/"No" deal column into 1/0
|
|
97
|
+
deal_text = data["Deal_Offered"].astype(str).str.strip().str.lower()
|
|
98
|
+
data["Deal_Binary"] = deal_text.map({"yes": 1, "no": 0})
|
|
99
|
+
data["Deal_Binary"] = data["Deal_Binary"].fillna(data["Deal_Binary"].mode()[0]).astype(int)
|
|
100
|
+
|
|
101
|
+
print("\nMissing values after cleaning:")
|
|
102
|
+
print(data.isnull().sum())
|
|
103
|
+
|
|
104
|
+
return data
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# -------------------------------------------------------------------
|
|
108
|
+
# STEP 3: SUMMARY STATISTICS
|
|
109
|
+
# -------------------------------------------------------------------
|
|
110
|
+
def show_summary_statistics(data):
|
|
111
|
+
print("\n" + "=" * 70)
|
|
112
|
+
print("STEP 3: SUMMARY STATISTICS")
|
|
113
|
+
print("=" * 70)
|
|
114
|
+
|
|
115
|
+
summary = pd.DataFrame({
|
|
116
|
+
"Mean": data[NUMBER_COLUMNS].mean(),
|
|
117
|
+
"Median": data[NUMBER_COLUMNS].median(),
|
|
118
|
+
"Mode": data[NUMBER_COLUMNS].mode().iloc[0],
|
|
119
|
+
"Minimum": data[NUMBER_COLUMNS].min(),
|
|
120
|
+
"Maximum": data[NUMBER_COLUMNS].max(),
|
|
121
|
+
"Std_Dev": data[NUMBER_COLUMNS].std(),
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
print(summary.round(2))
|
|
125
|
+
summary.to_csv(f"{OUTPUT_FOLDER}/summary_statistics.csv")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# -------------------------------------------------------------------
|
|
129
|
+
# STEP 4: NORMALIZE THE NUMBERS (SCALE 0 TO 1)
|
|
130
|
+
# -------------------------------------------------------------------
|
|
131
|
+
def normalize_data(data):
|
|
132
|
+
print("\n" + "=" * 70)
|
|
133
|
+
print("STEP 4: MIN-MAX NORMALIZATION")
|
|
134
|
+
print("=" * 70)
|
|
135
|
+
|
|
136
|
+
scaler = MinMaxScaler()
|
|
137
|
+
normalized = data.copy()
|
|
138
|
+
normalized[NUMBER_COLUMNS] = scaler.fit_transform(data[NUMBER_COLUMNS])
|
|
139
|
+
|
|
140
|
+
print(normalized[NUMBER_COLUMNS].head().round(3))
|
|
141
|
+
normalized.to_csv(f"{OUTPUT_FOLDER}/normalized_data.csv", index=False)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# -------------------------------------------------------------------
|
|
145
|
+
# STEP 5: FIND OUTLIERS (UNUSUAL VALUES)
|
|
146
|
+
# -------------------------------------------------------------------
|
|
147
|
+
def find_outliers(data):
|
|
148
|
+
print("\n" + "=" * 70)
|
|
149
|
+
print("STEP 5: OUTLIER DETECTION (IQR METHOD)")
|
|
150
|
+
print("=" * 70)
|
|
151
|
+
|
|
152
|
+
outlier_rows = []
|
|
153
|
+
|
|
154
|
+
for column in NUMBER_COLUMNS:
|
|
155
|
+
q1 = data[column].quantile(0.25)
|
|
156
|
+
q3 = data[column].quantile(0.75)
|
|
157
|
+
iqr = q3 - q1
|
|
158
|
+
lower_limit = q1 - 1.5 * iqr
|
|
159
|
+
upper_limit = q3 + 1.5 * iqr
|
|
160
|
+
|
|
161
|
+
is_outlier = (data[column] < lower_limit) | (data[column] > upper_limit)
|
|
162
|
+
count = is_outlier.sum()
|
|
163
|
+
|
|
164
|
+
outlier_rows.append([column, q1, q3, iqr, lower_limit, upper_limit, count])
|
|
165
|
+
print(f"{column}: {count} outliers (normal range {lower_limit:.2f} to {upper_limit:.2f})")
|
|
166
|
+
|
|
167
|
+
outlier_table = pd.DataFrame(
|
|
168
|
+
outlier_rows,
|
|
169
|
+
columns=["Column", "Q1", "Q3", "IQR", "Lower", "Upper", "Outlier_Count"]
|
|
170
|
+
)
|
|
171
|
+
outlier_table.to_csv(f"{OUTPUT_FOLDER}/outlier_summary.csv", index=False)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
# -------------------------------------------------------------------
|
|
175
|
+
# STEP 6: CORRELATION (WHICH NUMBERS MOVE TOGETHER)
|
|
176
|
+
# -------------------------------------------------------------------
|
|
177
|
+
def show_correlation(data):
|
|
178
|
+
print("\n" + "=" * 70)
|
|
179
|
+
print("STEP 6: CORRELATION")
|
|
180
|
+
print("=" * 70)
|
|
181
|
+
|
|
182
|
+
correlation = data[NUMBER_COLUMNS].corr()
|
|
183
|
+
print(correlation.round(3))
|
|
184
|
+
correlation.to_csv(f"{OUTPUT_FOLDER}/correlation_matrix.csv")
|
|
185
|
+
|
|
186
|
+
print("\nCorrelation with Sales:")
|
|
187
|
+
sales_correlation = correlation["Sales"].drop("Sales").sort_values(key=abs, ascending=False)
|
|
188
|
+
print(sales_correlation.round(3))
|
|
189
|
+
|
|
190
|
+
# Heatmap picture
|
|
191
|
+
plt.figure(figsize=(10, 6))
|
|
192
|
+
sns.heatmap(correlation, annot=True, cmap="coolwarm", fmt=".2f")
|
|
193
|
+
plt.title("Threadora Correlation Heatmap")
|
|
194
|
+
save_and_show_plot("01_correlation_heatmap.png")
|
|
195
|
+
|
|
196
|
+
return correlation
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# -------------------------------------------------------------------
|
|
200
|
+
# STEP 7: CHARTS AND GRAPHS
|
|
201
|
+
# -------------------------------------------------------------------
|
|
202
|
+
def make_charts(data):
|
|
203
|
+
print("\n" + "=" * 70)
|
|
204
|
+
print("STEP 7: CHARTS")
|
|
205
|
+
print("=" * 70)
|
|
206
|
+
|
|
207
|
+
data = data.sort_values("Date").reset_index(drop=True)
|
|
208
|
+
|
|
209
|
+
# Sales and footfall over time
|
|
210
|
+
plt.figure(figsize=(12, 5))
|
|
211
|
+
plt.plot(data.Date, data.Sales, marker="o")
|
|
212
|
+
plt.title("Daily Sales Over Time")
|
|
213
|
+
plt.xlabel("Date")
|
|
214
|
+
plt.ylabel("Sales (₹)")
|
|
215
|
+
plt.xticks(rotation=45)
|
|
216
|
+
save_and_show_plot("02_sales_over_time.png")
|
|
217
|
+
|
|
218
|
+
plt.figure(figsize=(12, 5))
|
|
219
|
+
plt.plot(data.Date, data.Footfall, marker="o")
|
|
220
|
+
plt.title("Daily Footfall Over Time")
|
|
221
|
+
plt.xlabel("Date")
|
|
222
|
+
plt.ylabel("Footfall")
|
|
223
|
+
plt.xticks(rotation=45)
|
|
224
|
+
save_and_show_plot("03_footfall_over_time.png")
|
|
225
|
+
|
|
226
|
+
# Scatterplots: each marketing signal vs Sales
|
|
227
|
+
scatter_plots = [
|
|
228
|
+
("Insta_Mentions", "Instagram Mentions vs Sales", "04_instagram_vs_sales.png"),
|
|
229
|
+
("Whatsapp_Inquiries", "WhatsApp Inquiries vs Sales", "05_whatsapp_vs_sales.png"),
|
|
230
|
+
("Ad_Spend", "Ad Spend vs Sales", "06_ad_spend_vs_sales.png"),
|
|
231
|
+
("Footfall", "Footfall vs Sales", "07_footfall_vs_sales.png"),
|
|
232
|
+
]
|
|
233
|
+
for column, title, file_name in scatter_plots:
|
|
234
|
+
plt.figure(figsize=(7, 5))
|
|
235
|
+
sns.scatterplot(data=data, x=column, y="Sales")
|
|
236
|
+
plt.title(title)
|
|
237
|
+
save_and_show_plot(file_name)
|
|
238
|
+
|
|
239
|
+
# Distributions
|
|
240
|
+
plt.figure(figsize=(7, 5))
|
|
241
|
+
sns.histplot(data.Sales, kde=True)
|
|
242
|
+
plt.title("Distribution of Daily Sales")
|
|
243
|
+
plt.xlabel("Sales (₹)")
|
|
244
|
+
save_and_show_plot("08_sales_histogram.png")
|
|
245
|
+
|
|
246
|
+
plt.figure(figsize=(7, 5))
|
|
247
|
+
sns.histplot(data.Footfall, kde=True)
|
|
248
|
+
plt.title("Distribution of Daily Footfall")
|
|
249
|
+
plt.xlabel("Footfall")
|
|
250
|
+
save_and_show_plot("09_footfall_histogram.png")
|
|
251
|
+
|
|
252
|
+
plt.figure(figsize=(7, 5))
|
|
253
|
+
sns.boxplot(y=data.Sales)
|
|
254
|
+
plt.title("Sales Boxplot")
|
|
255
|
+
save_and_show_plot("10_sales_boxplot.png")
|
|
256
|
+
|
|
257
|
+
# Pair plot (every number column against every other one)
|
|
258
|
+
pair_grid = sns.pairplot(data[["Footfall", "Sales", "Ad_Spend", "Insta_Mentions", "Whatsapp_Inquiries"]])
|
|
259
|
+
pair_grid.fig.suptitle("Threadora Pair Plot", y=1.02)
|
|
260
|
+
pair_grid.savefig(f"{OUTPUT_FOLDER}/11_pair_plot.png", dpi=150)
|
|
261
|
+
plt.show()
|
|
262
|
+
plt.close()
|
|
263
|
+
|
|
264
|
+
return data
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
# -------------------------------------------------------------------
|
|
268
|
+
# STEP 8: DEALS AND DAY-OF-WEEK PATTERNS
|
|
269
|
+
# -------------------------------------------------------------------
|
|
270
|
+
def analyze_deals_and_days(data):
|
|
271
|
+
print("\n" + "=" * 70)
|
|
272
|
+
print("STEP 8: DEAL ANALYSIS")
|
|
273
|
+
print("=" * 70)
|
|
274
|
+
|
|
275
|
+
signal_columns = ["Sales", "Footfall", "Ad_Spend", "Insta_Mentions", "Whatsapp_Inquiries"]
|
|
276
|
+
|
|
277
|
+
deal_summary = data.groupby("Deal_Offered")[signal_columns].mean()
|
|
278
|
+
print(deal_summary.round(2))
|
|
279
|
+
deal_summary.to_csv(f"{OUTPUT_FOLDER}/deal_analysis.csv")
|
|
280
|
+
|
|
281
|
+
print("\n" + "=" * 70)
|
|
282
|
+
print("STEP 9: DAY-OF-WEEK ANALYSIS")
|
|
283
|
+
print("=" * 70)
|
|
284
|
+
|
|
285
|
+
day_summary = data.groupby("Day")[signal_columns].mean()
|
|
286
|
+
day_summary = day_summary.reindex([day for day in DAY_ORDER if day in day_summary.index])
|
|
287
|
+
print(day_summary.round(2))
|
|
288
|
+
day_summary.to_csv(f"{OUTPUT_FOLDER}/day_analysis.csv")
|
|
289
|
+
|
|
290
|
+
plt.figure(figsize=(10, 5))
|
|
291
|
+
sns.barplot(x=day_summary.index, y=day_summary.Sales.values)
|
|
292
|
+
plt.title("Average Sales by Day")
|
|
293
|
+
plt.xticks(rotation=30)
|
|
294
|
+
plt.ylabel("Average Sales (₹)")
|
|
295
|
+
save_and_show_plot("12_daywise_sales.png")
|
|
296
|
+
|
|
297
|
+
plt.figure(figsize=(10, 5))
|
|
298
|
+
sns.barplot(x=day_summary.index, y=day_summary.Footfall.values)
|
|
299
|
+
plt.title("Average Footfall by Day")
|
|
300
|
+
plt.xticks(rotation=30)
|
|
301
|
+
plt.ylabel("Average Footfall")
|
|
302
|
+
save_and_show_plot("13_daywise_footfall.png")
|
|
303
|
+
|
|
304
|
+
return deal_summary, day_summary
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
# -------------------------------------------------------------------
|
|
308
|
+
# STEP 9: SALES TREND OVER TIME
|
|
309
|
+
# -------------------------------------------------------------------
|
|
310
|
+
def sales_trend(data):
|
|
311
|
+
print("\n" + "=" * 70)
|
|
312
|
+
print("STEP 10: TIME TREND")
|
|
313
|
+
print("=" * 70)
|
|
314
|
+
|
|
315
|
+
data["Day_Number"] = (data.Date - data.Date.min()).dt.days
|
|
316
|
+
|
|
317
|
+
trend_model = LinearRegression().fit(data[["Day_Number"]], data.Sales)
|
|
318
|
+
trend_prediction = trend_model.predict(data[["Day_Number"]])
|
|
319
|
+
|
|
320
|
+
print("Sales trend slope:", round(trend_model.coef_[0], 2))
|
|
321
|
+
print("Trend R2:", round(r2_score(data.Sales, trend_prediction), 4))
|
|
322
|
+
|
|
323
|
+
plt.figure(figsize=(12, 5))
|
|
324
|
+
plt.plot(data.Date, data.Sales, marker="o", label="Actual")
|
|
325
|
+
plt.plot(data.Date, trend_prediction, label="Linear Trend")
|
|
326
|
+
plt.title("Sales Trend")
|
|
327
|
+
plt.xticks(rotation=45)
|
|
328
|
+
plt.legend()
|
|
329
|
+
save_and_show_plot("14_sales_trend.png")
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
# -------------------------------------------------------------------
|
|
333
|
+
# STEP 10: LINEAR REGRESSION - PREDICT SALES AMOUNT
|
|
334
|
+
# -------------------------------------------------------------------
|
|
335
|
+
def predict_sales_amount(data):
|
|
336
|
+
print("\n" + "=" * 70)
|
|
337
|
+
print("STEP 11: LINEAR REGRESSION - PREDICT SALES")
|
|
338
|
+
print("=" * 70)
|
|
339
|
+
|
|
340
|
+
X = data[FEATURE_COLUMNS]
|
|
341
|
+
y = data.Sales
|
|
342
|
+
|
|
343
|
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)
|
|
344
|
+
|
|
345
|
+
model = LinearRegression().fit(X_train, y_train)
|
|
346
|
+
predictions = model.predict(X_test)
|
|
347
|
+
|
|
348
|
+
mae = mean_absolute_error(y_test, predictions)
|
|
349
|
+
mse = mean_squared_error(y_test, predictions)
|
|
350
|
+
rmse = np.sqrt(mse)
|
|
351
|
+
r2 = r2_score(y_test, predictions)
|
|
352
|
+
|
|
353
|
+
print(f"MAE = ₹{mae:.2f}")
|
|
354
|
+
print(f"MSE = {mse:.2f}")
|
|
355
|
+
print(f"RMSE = ₹{rmse:.2f}")
|
|
356
|
+
print(f"R2 = {r2:.4f}")
|
|
357
|
+
|
|
358
|
+
print("\nIntercept:", round(model.intercept_, 2))
|
|
359
|
+
coefficients = pd.DataFrame({"Feature": FEATURE_COLUMNS, "Coefficient": model.coef_})
|
|
360
|
+
print(coefficients.round(3))
|
|
361
|
+
coefficients.to_csv(f"{OUTPUT_FOLDER}/linear_coefficients.csv", index=False)
|
|
362
|
+
|
|
363
|
+
plt.figure(figsize=(7, 5))
|
|
364
|
+
plt.scatter(y_test, predictions)
|
|
365
|
+
low = min(y_test.min(), predictions.min())
|
|
366
|
+
high = max(y_test.max(), predictions.max())
|
|
367
|
+
plt.plot([low, high], [low, high])
|
|
368
|
+
plt.xlabel("Actual Sales")
|
|
369
|
+
plt.ylabel("Predicted Sales")
|
|
370
|
+
plt.title("Actual vs Predicted Sales")
|
|
371
|
+
save_and_show_plot("15_actual_vs_predicted.png")
|
|
372
|
+
|
|
373
|
+
return model
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
# -------------------------------------------------------------------
|
|
377
|
+
# STEP 11: LOGISTIC REGRESSION - PREDICT HIGH OR LOW SALES DAY
|
|
378
|
+
# -------------------------------------------------------------------
|
|
379
|
+
def predict_high_sales_day(data):
|
|
380
|
+
print("\n" + "=" * 70)
|
|
381
|
+
print("STEP 12: LOGISTIC REGRESSION - HIGH SALES DAY")
|
|
382
|
+
print("=" * 70)
|
|
383
|
+
|
|
384
|
+
data["High_Sales_Day"] = np.where(data.Sales > 5000, 1, 0)
|
|
385
|
+
print("\nClass counts:")
|
|
386
|
+
print(data.High_Sales_Day.value_counts())
|
|
387
|
+
|
|
388
|
+
X = data[FEATURE_COLUMNS]
|
|
389
|
+
y = data.High_Sales_Day
|
|
390
|
+
|
|
391
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
392
|
+
X, y, test_size=0.20, random_state=42, stratify=y
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
scaler = StandardScaler()
|
|
396
|
+
X_train_scaled = scaler.fit_transform(X_train)
|
|
397
|
+
X_test_scaled = scaler.transform(X_test)
|
|
398
|
+
|
|
399
|
+
model = LogisticRegression(class_weight="balanced", max_iter=1000)
|
|
400
|
+
model.fit(X_train_scaled, y_train)
|
|
401
|
+
|
|
402
|
+
predictions = model.predict(X_test_scaled)
|
|
403
|
+
|
|
404
|
+
accuracy = accuracy_score(y_test, predictions)
|
|
405
|
+
precision = precision_score(y_test, predictions, zero_division=0)
|
|
406
|
+
recall = recall_score(y_test, predictions, zero_division=0)
|
|
407
|
+
matrix = confusion_matrix(y_test, predictions)
|
|
408
|
+
|
|
409
|
+
print(f"Accuracy = {accuracy:.4f}")
|
|
410
|
+
print(f"Precision = {precision:.4f}")
|
|
411
|
+
print(f"Recall = {recall:.4f}")
|
|
412
|
+
print("\nConfusion Matrix:")
|
|
413
|
+
print(matrix)
|
|
414
|
+
print("\nClassification Report:")
|
|
415
|
+
print(classification_report(y_test, predictions, zero_division=0))
|
|
416
|
+
|
|
417
|
+
coefficients = pd.DataFrame({"Feature": FEATURE_COLUMNS, "Coefficient": model.coef_[0]})
|
|
418
|
+
coefficients.to_csv(f"{OUTPUT_FOLDER}/logistic_coefficients.csv", index=False)
|
|
419
|
+
|
|
420
|
+
plt.figure(figsize=(6, 5))
|
|
421
|
+
sns.heatmap(matrix, annot=True, fmt="d", cmap="Blues",
|
|
422
|
+
xticklabels=["Low", "High"], yticklabels=["Low", "High"])
|
|
423
|
+
plt.title("Logistic Regression Confusion Matrix")
|
|
424
|
+
plt.xlabel("Predicted")
|
|
425
|
+
plt.ylabel("Actual")
|
|
426
|
+
save_and_show_plot("16_confusion_matrix.png")
|
|
427
|
+
|
|
428
|
+
return model, scaler
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
# -------------------------------------------------------------------
|
|
432
|
+
# STEP 12: TRY A PREDICTION FOR A NEW DAY
|
|
433
|
+
# -------------------------------------------------------------------
|
|
434
|
+
def predict_new_day(sales_model, class_model, scaler):
|
|
435
|
+
print("\n" + "=" * 70)
|
|
436
|
+
print("STEP 13: EXAMPLE PREDICTION")
|
|
437
|
+
print("=" * 70)
|
|
438
|
+
|
|
439
|
+
new_day = pd.DataFrame({
|
|
440
|
+
"Ad_Spend": [1700],
|
|
441
|
+
"Footfall": [100],
|
|
442
|
+
"Whatsapp_Inquiries": [25],
|
|
443
|
+
"Insta_Mentions": [7],
|
|
444
|
+
})
|
|
445
|
+
|
|
446
|
+
predicted_sales = sales_model.predict(new_day)[0]
|
|
447
|
+
new_day_scaled = scaler.transform(new_day)
|
|
448
|
+
probabilities = class_model.predict_proba(new_day_scaled)[0]
|
|
449
|
+
predicted_class = class_model.predict(new_day_scaled)[0]
|
|
450
|
+
|
|
451
|
+
print(new_day)
|
|
452
|
+
print(f"Predicted Sales: ₹{predicted_sales:.2f}")
|
|
453
|
+
print(f"Probability of Low Sales: {probabilities[0] * 100:.2f}%")
|
|
454
|
+
print(f"Probability of High Sales: {probabilities[1] * 100:.2f}%")
|
|
455
|
+
print("Prediction:", "HIGH SALES DAY" if predicted_class == 1 else "LOW SALES DAY")
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
# -------------------------------------------------------------------
|
|
459
|
+
# STEP 13: FINAL BUSINESS SUMMARY
|
|
460
|
+
# -------------------------------------------------------------------
|
|
461
|
+
def print_business_summary(correlation, deal_summary, day_summary):
|
|
462
|
+
print("\n" + "=" * 70)
|
|
463
|
+
print("STEP 14: FINAL BUSINESS CONCLUSION")
|
|
464
|
+
print("=" * 70)
|
|
465
|
+
|
|
466
|
+
sales_correlation = correlation.Sales.drop("Sales").sort_values(key=abs, ascending=False)
|
|
467
|
+
print("Correlation with Sales:")
|
|
468
|
+
print(sales_correlation.round(3))
|
|
469
|
+
|
|
470
|
+
if not day_summary.empty:
|
|
471
|
+
best_day = day_summary.Sales.idxmax()
|
|
472
|
+
print(f"Highest average-sales day: {best_day} (₹{day_summary.loc[best_day, 'Sales']:.2f})")
|
|
473
|
+
|
|
474
|
+
if "Yes" in deal_summary.index and "No" in deal_summary.index:
|
|
475
|
+
print(f"Average sales with deal: ₹{deal_summary.loc['Yes', 'Sales']:.2f}")
|
|
476
|
+
print(f"Average sales without deal: ₹{deal_summary.loc['No', 'Sales']:.2f}")
|
|
477
|
+
|
|
478
|
+
print("""
|
|
479
|
+
Interpretation:
|
|
480
|
+
- Footfall has the strongest simple relationship with Sales in this dataset.
|
|
481
|
+
- WhatsApp inquiries also show a positive relationship with Sales.
|
|
482
|
+
- Instagram mentions show a positive but weaker relationship.
|
|
483
|
+
- Ad Spend has very little linear correlation with Sales in this dataset.
|
|
484
|
+
- Deal days have higher average sales in this dataset, but this does not prove causation.
|
|
485
|
+
- Day-of-week analysis can reveal useful weekly patterns.
|
|
486
|
+
- Linear Regression predicts continuous Sales.
|
|
487
|
+
- Logistic Regression predicts High Sales Day (Sales > ₹5000).
|
|
488
|
+
- Correlation/regression show associations, not proof that a marketing channel caused sales.
|
|
489
|
+
""")
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
# -------------------------------------------------------------------
|
|
493
|
+
# MAIN PROGRAM - RUNS ALL STEPS IN ORDER
|
|
494
|
+
# -------------------------------------------------------------------
|
|
495
|
+
def main():
|
|
496
|
+
data = load_data()
|
|
497
|
+
data = clean_data(data)
|
|
498
|
+
|
|
499
|
+
show_summary_statistics(data)
|
|
500
|
+
normalize_data(data)
|
|
501
|
+
find_outliers(data)
|
|
502
|
+
|
|
503
|
+
correlation = show_correlation(data)
|
|
504
|
+
data = make_charts(data)
|
|
505
|
+
deal_summary, day_summary = analyze_deals_and_days(data)
|
|
506
|
+
|
|
507
|
+
sales_trend(data)
|
|
508
|
+
sales_model = predict_sales_amount(data)
|
|
509
|
+
class_model, scaler = predict_high_sales_day(data)
|
|
510
|
+
predict_new_day(sales_model, class_model, scaler)
|
|
511
|
+
|
|
512
|
+
print_business_summary(correlation, deal_summary, day_summary)
|
|
513
|
+
|
|
514
|
+
data.to_csv(f"{OUTPUT_FOLDER}/threadora_cleaned_data.csv", index=False)
|
|
515
|
+
print(f"\nAll CSV results and graphs saved in: {OUTPUT_FOLDER}/")
|
|
516
|
+
print("\nPRACTICAL COMPLETED SUCCESSFULLY")
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
if __name__ == "__main__":
|
|
520
|
+
main()
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Create a Basic Sequence Workflow (Add Two Numbers)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
Steps:
|
|
5
|
+
|
|
6
|
+
Create a new Blank Process named AddTwoNumbers.
|
|
7
|
+
Drag a Sequence onto the design canvas.
|
|
8
|
+
Inside the sequence, drag an Input Dialog activity.
|
|
9
|
+
Set Label = "Enter first number"
|
|
10
|
+
Set Result = a new variable num1Text (type String)
|
|
11
|
+
|
|
12
|
+
Add a second Input Dialog activity.
|
|
13
|
+
Set Label = "Enter second number"
|
|
14
|
+
Set Result = new variable num2Text (type String)
|
|
15
|
+
|
|
16
|
+
Add an Assign activity:
|
|
17
|
+
Left side: create variable sum (type Int32)
|
|
18
|
+
Right side: Convert.ToInt32(num1Text) + Convert.ToInt32(num2Text)
|
|
19
|
+
|
|
20
|
+
Add a Message Box activity:
|
|
21
|
+
Text: "The sum is: " + sum.ToString()
|
|
22
|
+
|
|
23
|
+
Click Run, enter two numbers when asked, and confirm the message box shows the correct total.
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
Image and Text Automation (OCR)
|
|
28
|
+
|
|
29
|
+
Goal: Extract text written inside an image using Optical Character Recognition (OCR).
|
|
30
|
+
Packages Needed: UiPath.OCR.Activities (install via Manage Packages)
|
|
31
|
+
Steps:
|
|
32
|
+
|
|
33
|
+
Go to Manage Packages → All Packages, search UiPath.OCR.Activities, and install it.
|
|
34
|
+
Add a Get OCR Text activity to your workflow.
|
|
35
|
+
In its properties, set:
|
|
36
|
+
OCR Engine = Microsoft OCR (built-in, no API key needed)
|
|
37
|
+
Image/Path = full path of your image file (e.g., "C:\Images\sample.png")
|
|
38
|
+
Text output = new variable extractedText (type String)
|
|
39
|
+
|
|
40
|
+
Add a Message Box activity with Text = extractedText.
|
|
41
|
+
Run the workflow — the text found inside the image will pop up in the message box.
|
|
42
|
+
|
|
43
|
+
(Alternative: use the Screen Scraping wizard from the Design tab, select “Native/OCR” method, and drag a box over the text you want to capture on screen.)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
PDF Data Extraction (Fee Receipt)
|
|
48
|
+
|
|
49
|
+
Goal: Read a PDF file and pull out one specific value (the Total amount).
|
|
50
|
+
Packages Needed: UiPath.PDF.Activities
|
|
51
|
+
Steps:
|
|
52
|
+
|
|
53
|
+
Install the UiPath.PDF package from Manage Packages if not already present.
|
|
54
|
+
Drag a Read PDF Text activity.
|
|
55
|
+
File Path = path of the fee receipt PDF
|
|
56
|
+
Text output = variable pdfText (type String)
|
|
57
|
+
|
|
58
|
+
Add an Assign activity to pull out the total using Regex:
|
|
59
|
+
Variable totalAmount (type String) = System.Text.RegularExpressions.Regex.Match(pdfText, "Total.?(\d+[,.]?\d)").Groups(1).Value
|
|
60
|
+
(Adjust the pattern slightly to match how “Total” is written in your receipt, e.g. "Total Amount" or "Total: ₹".)
|
|
61
|
+
|
|
62
|
+
Add a Message Box with Text = "Total Amount: " + totalAmount.
|
|
63
|
+
Run and confirm the correct total is displayed.
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
Keyboard Events (Ctrl+A, Ctrl+C, Ctrl+V)
|
|
68
|
+
|
|
69
|
+
Goal: Simulate keyboard shortcuts to select, copy, and paste text, then show what was copied.
|
|
70
|
+
Activities Used: Send Hotkey, Get From Clipboard, Message Box
|
|
71
|
+
Steps:
|
|
72
|
+
|
|
73
|
+
Open any webpage with a text box (or a Notepad file with some text already typed).
|
|
74
|
+
Use Indicate on Screen to select the text field.
|
|
75
|
+
Add a Send Hotkey activity targeting that field: Key = Ctrl+A (select all text).
|
|
76
|
+
Add another Send Hotkey: Key = Ctrl+C (copy the selected text).
|
|
77
|
+
Add a Get From Clipboard activity → output variable copiedText (String).
|
|
78
|
+
Open Notepad (or another field), indicate it, and add a Send Hotkey: Key = Ctrl+V to paste there.
|
|
79
|
+
Add a Message Box with Text = copiedText to display what was copied.
|
|
80
|
+
Run and confirm the same text appears in the message box and gets pasted correctly.
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
Data Scraping (E-commerce Website)
|
|
84
|
+
|
|
85
|
+
Goal: Automatically pull structured data (Product Name, Price, Rating) for at least 10 products from a shopping website into Excel.
|
|
86
|
+
Steps:
|
|
87
|
+
|
|
88
|
+
Open a browser and navigate to any e-commerce listing/search results page (e.g., a search on Amazon or Flipkart) that shows multiple products with name, price, and rating.
|
|
89
|
+
In UiPath Studio, go to Design → Extract Data (the Data Scraping wizard) and click on the page.
|
|
90
|
+
Click the first product’s name, then click a second product’s name — the wizard detects the repeating pattern and highlights all matching products.
|
|
91
|
+
Click Extract Correlated Data and repeat the “click first, click second” step for the Price field, then again for the Rating field, so all three columns line up in the same table.
|
|
92
|
+
When asked “Extract data for all pages?”, choose No if 10 products already fit on one page, or set the number of pages needed.
|
|
93
|
+
Finish the wizard — it automatically inserts activities and creates a DataTable variable, e.g. dtProducts.
|
|
94
|
+
Add a Write Range activity (inside an Excel/Workbook scope) to write dtProducts into a new file, e.g. Products.xlsx.
|
|
95
|
+
Run the workflow and open Products.xlsx to confirm all 10+ rows (Name, Price, Rating) were captured correctly.
|