npdrop 0.3.0__py3-none-any.whl

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.
myml/data/train.txt ADDED
@@ -0,0 +1,618 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ import nltk
4
+ from nltk.tokenize import word_tokenize
5
+ from nltk.util import ngrams
6
+ from nltk.stem import PorterStemmer, WordNetLemmatizer
7
+
8
+ nltk.download("punkt", quiet=True)
9
+ nltk.download("punkt_tab", quiet=True)
10
+ nltk.download("wordnet", quiet=True)
11
+
12
+ # --- Pandas Cleaning & Outlier Handling ---
13
+ df = pd.read_csv("data.csv")
14
+ print(df.info())
15
+ print(df.head())
16
+
17
+ # Convert numeric column safely (invalid strings -> NaN -> median)
18
+ if "Age" in df.columns:
19
+ df["Age"] = pd.to_numeric(df["Age"], errors="coerce")
20
+ df["Age"] = df["Age"].fillna(df["Age"].median())
21
+
22
+ # Inspect categorical column (e.g., Region)
23
+ if "Region" in df.columns:
24
+ print(df["Region"].value_counts(dropna=False))
25
+
26
+ # IQR outlier replacement with mean (example on numeric column)
27
+ col = df.select_dtypes(include=[np.number]).columns[0]
28
+ q1 = df[col].quantile(0.25)
29
+ q3 = df[col].quantile(0.75)
30
+ iqr = q3 - q1
31
+ lower_iqr = q1 - 1.5 * iqr
32
+ upper_iqr = q3 + 1.5 * iqr
33
+ mean_val = df[col].mean()
34
+ df[col] = df[col].mask((df[col] < lower_iqr) | (df[col] > upper_iqr), mean_val)
35
+
36
+ # Drop target/cluster column when building features
37
+ # X = df.drop("target", axis=1)
38
+ # y = df["target"]
39
+
40
+ # --- NLTK Tokenization, N-grams, Stemming & Lemmatization ---
41
+ txt = "i am dilip"
42
+ tokens = word_tokenize(txt)
43
+ ps = PorterStemmer()
44
+ wl = WordNetLemmatizer()
45
+
46
+ print("Tokens:", tokens)
47
+ print("Bigrams:", list(ngrams(tokens, 2)))
48
+ print("Stemmed:", [ps.stem(w) for w in tokens])
49
+ print("Lemmatized:", [wl.lemmatize(w, pos="v") for w in tokens])
50
+
51
+
52
+ import pandas as pd
53
+ import matplotlib.pyplot as plt
54
+ from sklearn.model_selection import train_test_split
55
+ from sklearn.linear_model import LinearRegression
56
+ from sklearn.metrics import mean_squared_error, r2_score
57
+
58
+ df = pd.read_csv("data.csv")
59
+ X = df[["Hours"]] # 2D DataFrame (replace with your feature column(s))
60
+ y = df["Score"] # 1D continuous target
61
+
62
+ X_train, X_test, y_train, y_test = train_test_split(
63
+ X, y, test_size=0.2, random_state=42
64
+ )
65
+
66
+ model = LinearRegression()
67
+ model.fit(X_train, y_train)
68
+ y_pred = model.predict(X_test)
69
+
70
+ print("Slope (m):", model.coef_[0])
71
+ print("Intercept (c):", model.intercept_)
72
+ print("MSE:", mean_squared_error(y_test, y_pred))
73
+ print("R2 Score:", r2_score(y_test, y_pred))
74
+
75
+ plt.figure(figsize=(7, 4))
76
+ plt.scatter(X, y, color="blue", label="Actual Data")
77
+ plt.plot(X, model.predict(X), color="red", linewidth=2, label="Regression Line")
78
+ plt.xlabel(X.columns[0])
79
+ plt.ylabel(y.name)
80
+ plt.title("Linear Regression Fit")
81
+ plt.legend()
82
+ plt.show()
83
+
84
+
85
+ import numpy as np
86
+ import pandas as pd
87
+ import matplotlib.pyplot as plt
88
+ from sklearn.model_selection import train_test_split
89
+ from sklearn.linear_model import LogisticRegression
90
+ from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
91
+
92
+ df = pd.read_csv("data.csv")
93
+ X = df[["Hours"]] # 2D DataFrame
94
+ y = df["Passed"] # 1D binary class labels (0 / 1)
95
+
96
+ X_train, X_test, y_train, y_test = train_test_split(
97
+ X, y, test_size=0.2, random_state=42
98
+ )
99
+
100
+ model = LogisticRegression()
101
+ model.fit(X_train, y_train)
102
+
103
+ y_pred = model.predict(X_test)
104
+ y_prob = model.predict_proba(X_test)[:, 1]
105
+
106
+ print("Accuracy:", accuracy_score(y_test, y_pred))
107
+ print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
108
+ print("Classification Report:\n", classification_report(y_test, y_pred))
109
+
110
+ x_grid = np.linspace(X.iloc[:, 0].min(), X.iloc[:, 0].max(), 200).reshape(-1, 1)
111
+ prob_grid = model.predict_proba(x_grid)[:, 1]
112
+
113
+ plt.figure(figsize=(7, 4))
114
+ plt.scatter(X, y, color="blue", label="Actual Class (0 / 1)")
115
+ plt.plot(x_grid, prob_grid, color="red", linewidth=2, label="Sigmoid Probability")
116
+ plt.axhline(0.5, color="gray", linestyle="--", label="Threshold (0.5)")
117
+ plt.xlabel(X.columns[0])
118
+ plt.ylabel("Probability / Class")
119
+ plt.title("Logistic Regression Sigmoid Curve")
120
+ plt.legend()
121
+ plt.show()
122
+
123
+ import pandas as pd
124
+ import seaborn as sns
125
+ import matplotlib.pyplot as plt
126
+ from sklearn.cluster import KMeans
127
+
128
+ df = pd.read_csv("Mall_Customers.csv")
129
+ X = df[["Annual Income (k$)", "Spending Score (1-100)"]]
130
+
131
+ # Elbow Method (WCSS)
132
+ wcss = []
133
+ for k in range(1, 11):
134
+ km = KMeans(n_clusters=k, random_state=42, n_init="auto")
135
+ km.fit(X)
136
+ wcss.append(km.inertia_)
137
+
138
+ plt.figure(figsize=(7, 4))
139
+ sns.lineplot(x=range(1, 11), y=wcss, marker="o")
140
+ plt.title("Elbow Method for Optimal k")
141
+ plt.xlabel("Number of Clusters (k)")
142
+ plt.ylabel("WCSS (Inertia)")
143
+ plt.xticks(range(1, 11))
144
+ plt.show()
145
+
146
+ # Fit K-Means with k = 5
147
+ model = KMeans(n_clusters=5, random_state=42, n_init="auto")
148
+ df["cluster"] = model.fit_predict(X)
149
+
150
+ plt.figure(figsize=(8, 5))
151
+ sns.scatterplot(
152
+ data=df,
153
+ x="Annual Income (k$)",
154
+ y="Spending Score (1-100)",
155
+ hue="cluster",
156
+ palette="viridis",
157
+ s=60
158
+ )
159
+ centroids = model.cluster_centers_
160
+ plt.scatter(
161
+ centroids[:, 0],
162
+ centroids[:, 1],
163
+ color="red",
164
+ marker="X",
165
+ s=200,
166
+ label="Centroids"
167
+ )
168
+ plt.title("Customer Segments (K-Means, k=5)")
169
+ plt.xlabel("Annual Income (k$)")
170
+ plt.ylabel("Spending Score (1-100)")
171
+ plt.legend()
172
+ plt.show()
173
+
174
+
175
+
176
+
177
+ import pandas as pd
178
+ from sklearn.model_selection import train_test_split
179
+ from sklearn.tree import DecisionTreeClassifier
180
+ from sklearn.metrics import accuracy_score, classification_report
181
+
182
+ df = pd.read_csv("data.csv")
183
+ X = df.drop("target", axis=1)
184
+ y = df["target"]
185
+
186
+ X_train, X_test, y_train, y_test = train_test_split(
187
+ X, y, test_size=0.2, random_state=42
188
+ )
189
+
190
+ model = DecisionTreeClassifier(random_state=42)
191
+ model.fit(X_train, y_train)
192
+ y_pred = model.predict(X_test)
193
+
194
+ print("Accuracy:", accuracy_score(y_test, y_pred))
195
+ print(classification_report(y_test, y_pred))
196
+
197
+ import pandas as pd
198
+ from sklearn.model_selection import train_test_split
199
+ from sklearn.tree import DecisionTreeRegressor
200
+ from sklearn.metrics import mean_squared_error, r2_score
201
+
202
+ df = pd.read_csv("data.csv")
203
+ X = df.drop("target", axis=1)
204
+ y = df["target"]
205
+
206
+ X_train, X_test, y_train, y_test = train_test_split(
207
+ X, y, test_size=0.2, random_state=42
208
+ )
209
+
210
+ model = DecisionTreeRegressor(random_state=42)
211
+ model.fit(X_train, y_train)
212
+ y_pred = model.predict(X_test)
213
+
214
+ print("MSE:", mean_squared_error(y_test, y_pred))
215
+ print("R2 Score:", r2_score(y_test, y_pred))
216
+
217
+
218
+ import pandas as pd
219
+ from sklearn.model_selection import train_test_split
220
+ from sklearn.ensemble import RandomForestClassifier
221
+ from sklearn.metrics import accuracy_score, classification_report
222
+
223
+ df = pd.read_csv("data.csv")
224
+ X = df.drop("target", axis=1)
225
+ y = df["target"]
226
+
227
+ X_train, X_test, y_train, y_test = train_test_split(
228
+ X, y, test_size=0.2, random_state=42
229
+ )
230
+
231
+ model = RandomForestClassifier(n_estimators=100, random_state=42)
232
+ model.fit(X_train, y_train)
233
+ y_pred = model.predict(X_test)
234
+
235
+ print("Accuracy:", accuracy_score(y_test, y_pred))
236
+ print(classification_report(y_test, y_pred))
237
+
238
+ import pandas as pd
239
+ from sklearn.model_selection import train_test_split
240
+ from sklearn.ensemble import RandomForestRegressor
241
+ from sklearn.metrics import mean_squared_error, r2_score
242
+
243
+ df = pd.read_csv("data.csv")
244
+ X = df.drop("target", axis=1)
245
+ y = df["target"]
246
+
247
+ X_train, X_test, y_train, y_test = train_test_split(
248
+ X, y, test_size=0.2, random_state=42
249
+ )
250
+
251
+ model = RandomForestRegressor(n_estimators=100, random_state=42)
252
+ model.fit(X_train, y_train)
253
+ y_pred = model.predict(X_test)
254
+
255
+ print("MSE:", mean_squared_error(y_test, y_pred))
256
+ print("R2 Score:", r2_score(y_test, y_pred))
257
+
258
+ import pandas as pd
259
+ from sklearn.model_selection import train_test_split
260
+ from sklearn.svm import SVC
261
+ from sklearn.metrics import accuracy_score, classification_report
262
+
263
+ df = pd.read_csv("data.csv")
264
+ X = df.drop("target", axis=1)
265
+ y = df["target"]
266
+
267
+ X_train, X_test, y_train, y_test = train_test_split(
268
+ X, y, test_size=0.2, random_state=42
269
+ )
270
+
271
+ model = SVC()
272
+ model.fit(X_train, y_train)
273
+ y_pred = model.predict(X_test)
274
+
275
+ print("Accuracy:", accuracy_score(y_test, y_pred))
276
+ print(classification_report(y_test, y_pred))
277
+
278
+ import pandas as pd
279
+ from sklearn.model_selection import train_test_split
280
+ from sklearn.svm import SVR
281
+ from sklearn.metrics import mean_squared_error, r2_score
282
+
283
+ df = pd.read_csv("data.csv")
284
+ X = df.drop("target", axis=1)
285
+ y = df["target"]
286
+
287
+ X_train, X_test, y_train, y_test = train_test_split(
288
+ X, y, test_size=0.2, random_state=42
289
+ )
290
+
291
+ model = SVR()
292
+ model.fit(X_train, y_train)
293
+ y_pred = model.predict(X_test)
294
+
295
+ print("MSE:", mean_squared_error(y_test, y_pred))
296
+ print("R2 Score:", r2_score(y_test, y_pred))
297
+
298
+ import pandas as pd
299
+ from sklearn.model_selection import train_test_split
300
+ from sklearn.neighbors import KNeighborsClassifier
301
+ from sklearn.metrics import accuracy_score, classification_report
302
+
303
+ df = pd.read_csv("data.csv")
304
+ X = df.drop("target", axis=1)
305
+ y = df["target"]
306
+
307
+ X_train, X_test, y_train, y_test = train_test_split(
308
+ X, y, test_size=0.2, random_state=42
309
+ )
310
+
311
+ model = KNeighborsClassifier(n_neighbors=5)
312
+ model.fit(X_train, y_train)
313
+ y_pred = model.predict(X_test)
314
+
315
+ print("Accuracy:", accuracy_score(y_test, y_pred))
316
+ print(classification_report(y_test, y_pred))
317
+
318
+ import pandas as pd
319
+ from sklearn.model_selection import train_test_split
320
+ from sklearn.neighbors import KNeighborsRegressor
321
+ from sklearn.metrics import mean_squared_error, r2_score
322
+
323
+ df = pd.read_csv("data.csv")
324
+ X = df.drop("target", axis=1)
325
+ y = df["target"]
326
+
327
+ X_train, X_test, y_train, y_test = train_test_split(
328
+ X, y, test_size=0.2, random_state=42
329
+ )
330
+
331
+ model = KNeighborsRegressor(n_neighbors=5)
332
+ model.fit(X_train, y_train)
333
+ y_pred = model.predict(X_test)
334
+
335
+ print("MSE:", mean_squared_error(y_test, y_pred))
336
+ print("R2 Score:", r2_score(y_test, y_pred))
337
+
338
+ import numpy as np
339
+ import matplotlib.pyplot as plt
340
+ import tensorflow as tf
341
+ from tensorflow import keras
342
+ from tensorflow.keras import Sequential
343
+ from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense
344
+
345
+ (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
346
+ x_train = x_train.reshape(-1, 28, 28, 1) / 255.0
347
+ x_test = x_test.reshape(-1, 28, 28, 1) / 255.0
348
+
349
+ model = Sequential([
350
+ Input(shape=(28, 28, 1)),
351
+ Conv2D(32, 3, activation="relu"),
352
+ MaxPooling2D(),
353
+ Flatten(),
354
+ Dense(128, activation="relu"),
355
+ Dense(10, activation="softmax")
356
+ ])
357
+
358
+ model.compile(
359
+ optimizer="adam",
360
+ loss="sparse_categorical_crossentropy",
361
+ metrics=["accuracy"]
362
+ )
363
+
364
+ model.fit(x_train, y_train, epochs=5, batch_size=32, validation_split=0.1)
365
+
366
+ test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
367
+ print("Test Accuracy:", test_acc)
368
+
369
+ y_pred = model.predict(x_test)
370
+
371
+ plt.figure(figsize=(3, 3))
372
+ plt.imshow(x_train[4].squeeze(), cmap="gray")
373
+ plt.title(f"Train Label: {y_train[4]}")
374
+ plt.axis("off")
375
+ plt.show()
376
+
377
+ plt.figure(figsize=(12, 3))
378
+ for i in range(10):
379
+ plt.subplot(1, 10, i + 1)
380
+ plt.imshow(x_test[i].squeeze(), cmap="gray")
381
+ plt.title(f"Pred: {np.argmax(y_pred[i])}")
382
+ plt.axis("off")
383
+ plt.tight_layout()
384
+ plt.show()
385
+
386
+ import pandas as pd
387
+ import seaborn as sns
388
+ import matplotlib.pyplot as plt
389
+ from sklearn.cluster import KMeans
390
+
391
+ df = pd.read_csv("Mall_Customers.csv")
392
+ x=df[['Annual Income (k$)','Spending Score (1-100)']]
393
+
394
+
395
+ for k in range(1, 11):
396
+ km = KMeans(n_clusters=k, random_state=42,)
397
+ km.fit(X)
398
+ wcss.append(km.inertia_)
399
+
400
+
401
+ sns.lineplot(x=range(1,11),y=wcss,marker='o')
402
+
403
+ model = KMeans(n_clusters=5, random_state=42)
404
+ df["cluster"] = model.fit_predict(X)
405
+ sns.scatterplot(data=df,x='Annual Income (k$)',y='Spending Score (1-100)',hue='cluster')
406
+
407
+
408
+
409
+ q1=df['Annual Income (k$)'].quantile(0.25)
410
+ q3=df['Annual Income (k$)'].quantile(0.75)
411
+ iqr=q3-q1
412
+ upper_limit=q1+1.5*iqr
413
+ lower_limit=q3-1.5*iqr
414
+ men=df['Annual Income (k$)'].mean()
415
+ df['Annual Income (k$)']=df['Annual Income (k$)'].mask((df['Annual Income (k$)']>upper_limit)|(df['Annual Income (k$)']<lower_limit),men)
416
+
417
+
418
+
419
+ men=df['Spending Score (1-100)'].mean()
420
+ std=df['Spending Score (1-100)'].std()
421
+ lower_limit=men-3*std
422
+
423
+ import pandas as pd
424
+ import matplotlib.pyplot as plt
425
+ from sklearn.model_selection import train_test_split
426
+ from sklearn.linear_model import LinearRegression
427
+ from sklearn.metrics import mean_squared_error, r2_score
428
+
429
+ #
430
+ df = pd.read_csv("data.csv")
431
+
432
+ df.dropna()
433
+ df.drop_duplicates()
434
+
435
+ df=pd.get_dummies(df,drop_first=True,dtype=int)
436
+
437
+ X = df.drop('Score',axis=1)
438
+ y = df["Score"]
439
+
440
+ X_train, X_test, y_train, y_test = train_test_split(
441
+ X, y, test_size=0.2, random_state=42
442
+ )
443
+
444
+ model = LinearRegression()
445
+ model.fit(X_train, y_train)
446
+
447
+ y_pred = model.predict(X_test)
448
+ print("Slope (m):", model.coef_[0])
449
+ print("Intercept (c):", model.intercept_)
450
+ print("MSE:", mean_squared_error(y_test, y_pred))
451
+ print("R2 Score:", r2_score(y_test, y_pred))
452
+
453
+ plt.scatter(X, y, color="blue", label="Actual Data")
454
+ plt.plot(X, model.predict(X), color="red", linewidth=2, label="Regression Line")
455
+ plt.xlabel(X.columns[0])
456
+ plt.ylabel(y.name)
457
+ plt.title("Linear Regression Fit")
458
+ plt.legend()
459
+ plt.show()
460
+
461
+ import numpy as np
462
+ import pandas as pd
463
+ import matplotlib.pyplot as plt
464
+ from sklearn.model_selection import train_test_split
465
+ from sklearn.linear_model import LogisticRegression
466
+ from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
467
+
468
+ df = pd.read_csv("data.csv")
469
+
470
+ X = df[["Hours"]]
471
+ y = df["Passed"]
472
+
473
+ X_train, X_test, y_train, y_test = train_test_split(
474
+ X, y, test_size=0.2, random_state=42
475
+ )
476
+
477
+ model = LogisticRegression()
478
+ model.fit(X_train, y_train)
479
+
480
+
481
+ y_pred = model.predict(X_test)
482
+
483
+ print("Accuracy:", accuracy_score(y_test, y_pred))
484
+ print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
485
+ print("Classification Report:\n", classification_report(y_test, y_pred))
486
+
487
+ x_grid = np.linspace(X.iloc[:, 0].min(), X.iloc[:, 0].max(), 200).reshape(-1, 1)
488
+ prob_grid = model.predict_proba(x_grid)[:, 1]
489
+
490
+ plt.scatter(X, y, color="blue", label="Actual Class (0 / 1)")
491
+ plt.plot(x_grid, prob_grid, color="red", linewidth=2, label="Predicted Probability (Class 1)")
492
+ plt.axhline(0.5, color="gray", linestyle="--", label="Decision Threshold (0.5)")
493
+ plt.xlabel(X.columns[0])
494
+ plt.ylabel("Probability / Target Class")
495
+ plt.title("Logistic Regression Sigmoid Curve")
496
+ plt.legend()
497
+ plt.show()
498
+
499
+ from sklearn.tree import DecisionTreeClassifier
500
+ model = DecisionTreeClassifier(random_state=42)
501
+ model.fit(X_train, y_train)
502
+ y_pred = model.predict(X_test)
503
+
504
+
505
+ from sklearn.ensemble import RandomForestClassifier
506
+ model = RandomForestClassifier(random_state=42)
507
+ model.fit(X_train, y_train)
508
+ y_pred = model.predict(X_test)
509
+
510
+
511
+ from sklearn.svm import SVC
512
+ model = SVC()
513
+ model.fit(X_train, y_train)
514
+ y_pred = model.predict(X_test)
515
+
516
+
517
+ from sklearn.neighbors import KNeighborsClassifier
518
+ model = KNeighborsClassifier(n_neighbors=5)
519
+ model.fit(X_train, y_train)
520
+ y_pred = model.predict(X_test)
521
+
522
+ import nltk
523
+ from nltk.util import ngrams
524
+ from nltk.stem import WordNetLemmatizer,PorterStemmer
525
+ from nltk.tokenize import word_tokenize
526
+
527
+ nltk.download('punket')
528
+ nltk.download('punket_tab')
529
+ nltk.download('wordnet')
530
+
531
+ txt='i am dilip'
532
+ word=word_tokenize(txt)
533
+
534
+ wl=WordNetLemmatizer()
535
+ ps=PorterStemmer()
536
+
537
+ print('PorterStemmer',[ps.stem(word) for word in word])
538
+ print('WordNetLemmatizer',[wl.lemmatize(word) for word in word])
539
+
540
+ ug=list(ngrams(word,1))
541
+ bg=list(ngrams(word,2))
542
+ tg=list(ngrams(word,3))
543
+ print(ug)
544
+ print(bg)
545
+ print(tg)
546
+
547
+
548
+ import seaborn as sns
549
+ import matplotlib.pyplot as plt
550
+
551
+ # 1. Heatmap (Correlation Matrix)
552
+ sns.heatmap(df.corr(numeric_only=True), annot=True, cmap="coolwarm")
553
+ plt.show()
554
+
555
+ # 2. Box Plot (Outliers & Distribution)
556
+ sns.boxplot(data=df, x="col1", y="col2")
557
+ plt.show()
558
+
559
+ # 3. Scatter Plot (Relationship / Clusters)
560
+ sns.scatterplot(data=df, x="col1", y="col2", hue="cluster")
561
+ plt.show()
562
+
563
+ # 4. Line Plot (Trends / Elbow Method)
564
+ sns.lineplot(x=range(1, 11), y=wcss, marker="o")
565
+ plt.show()
566
+
567
+ # 5. Bar Plot / Count Plot (Categories)
568
+ sns.countplot(data=df, x="category_col")
569
+ plt.show()
570
+
571
+ # 6. Histogram / Distribution Plot (Frequency)
572
+ sns.histplot(df["col1"], bins=10, kde=True)
573
+ plt.show()
574
+
575
+ # 7. Pie Chart (Percentage Share)
576
+ df["category_col"].value_counts().plot.pie(autopct="%1.1f%%")
577
+ plt.show()
578
+
579
+ # 8. Pair Plot (All Numerical Column Pairs)
580
+ sns.pairplot(df, hue="target")
581
+ plt.show()
582
+
583
+ from functools import reduce
584
+ import pandas as pd
585
+
586
+ nums = [1, 2, 3, 4, 5, 6]
587
+
588
+ # 1. lambda (small anonymous function)
589
+ add_ten = lambda x: x + 10
590
+ print(add_ten(5)) # 15
591
+
592
+ # 2. map() (apply function to every item -> wrap in list())
593
+ squares = list(map(lambda x: x ** 2, nums))
594
+ print(squares) # [1, 4, 9, 16, 25, 36]
595
+
596
+ # 3. filter() (keep items where condition is True -> wrap in list())
597
+ evens = list(filter(lambda x: x % 2 == 0, nums))
598
+ print(evens) # [2, 4, 6]
599
+
600
+ # 4. reduce() (fold sequence into a single value)
601
+ total = reduce(lambda a, b: a + b, nums)
602
+ print(total) # 21
603
+
604
+ # 5. List Comprehension (clean Python alternative to map + filter)
605
+ even_squares = [x ** 2 for x in nums if x % 2 == 0]
606
+ print(even_squares) # [4, 16, 36]
607
+
608
+ # 6. fillna() (replace missing/NaN values in Pandas)
609
+ df = pd.DataFrame({"Score": [80.0, None, 90.0, None], "Grade": ["A", None, "B", "A"]})
610
+ df["Score"] = df["Score"].fillna(df["Score"].mean()) # fill numeric NaNs with mean/median
611
+ df["Grade"] = df["Grade"].fillna(df["Grade"].mode()[0]) # fill categorical NaNs with mode
612
+ print(df)
613
+
614
+ # 7. Pandas Series.map() & apply() (value mapping & custom row/cell logic)
615
+ df["Pass"] = df["Score"].map(lambda s: 1 if s >= 85 else 0)
616
+ print(df)
617
+
618
+
myml/magic.py ADDED
@@ -0,0 +1,37 @@
1
+ """Optional IPython %myml line magic and completion integration."""
2
+
3
+
4
+ def enable_magic():
5
+ try:
6
+ from IPython import get_ipython
7
+ shell = get_ipython()
8
+ if shell is None:
9
+ return False
10
+ try:
11
+ shell.Completer.greedy = True
12
+ except Exception:
13
+ pass
14
+
15
+ try:
16
+ from .suggester import install_matcher
17
+ install_matcher(shell)
18
+ except Exception:
19
+ pass
20
+
21
+ if getattr(shell, "_myml_magic_registered", False):
22
+ return True
23
+
24
+ from IPython.core.magic import register_line_magic
25
+ from .core import ask, list_templates
26
+
27
+ @register_line_magic
28
+ def myml(line):
29
+ text = line.strip()
30
+ if text:
31
+ return ask(text)
32
+ return list_templates()
33
+
34
+ shell._myml_magic_registered = True
35
+ return True
36
+ except Exception:
37
+ return False