Introduction to Data Science
No internet in the exam. The built-ins below ship inside the packages; the red ones try to download and will fail.
| Call | What you get | Offline? |
|---|---|---|
| load_iris() | 150 flowers · 4 features · 3 speciesfrom sklearn.datasets | Works |
| load_wine() | 178 wines · 13 features · 3 classesfrom sklearn.datasets | Works |
| load_breast_cancer() | 569 tumours · 30 features · 2 classesfrom sklearn.datasets | Works |
| load_digits() | 1797 8×8 images · 64 features · 10 digitsfrom sklearn.datasets | Works |
| load_diabetes() | 442 patients · 10 features · regression targetfrom sklearn.datasets | Works |
| make_classification() / make_blobs() / make_regression() / make_moons() | Generate any size you wantfrom sklearn.datasets | Works |
| px.data.iris() / tips() / gapminder() / stocks() | Ships inside plotlyimport plotly.express as px | Works |
| nx.karate_club_graph() | 34-node social networkimport networkx as nx | Works |
| sns.load_dataset('titanic' | 'tips' | 'iris') | Downloads from GitHubFails with no internet unless it was cached in ~/seaborn-data before | Needs internet |
| fetch_california_housing() / fetch_openml() | Downloads on first useUse load_diabetes() or a hand-made DataFrame instead | Needs internet |
| nltk.download('stopwords') | Downloads NLTK dataUse sklearn's ENGLISH_STOP_WORDS instead | Needs internet |
When the question names a dataset that isn't on the system, type a small DataFrame like these (six to twelve rows is plenty).
Stats, regression, preprocessing
import pandas as pd
import numpy as np
df = pd.DataFrame({
'Name': ['Asha', 'Rahul', 'Meera', 'Arjun', 'Priya', 'Karan', 'Dev', 'Sara'],
'Hours': [2, 4, 6, 8, 5, 7, 3, 9],
'Attendance': [60, 75, 85, 95, 80, 90, 70, 98],
'Marks': [45, 58, 70, 88, 66, 79, 52, 93]})
df['Pass'] = (df['Marks'] >= 60).astype(int)
print(df)
print(df.describe())Titanic was asked but no CSV is on the system
import pandas as pd
import numpy as np
df = pd.DataFrame({
'Survived': [0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0],
'Pclass': [3, 1, 3, 1, 3, 3, 1, 3, 2, 3, 2, 1],
'Sex': ['male', 'female', 'female', 'female', 'male', 'male',
'male', 'female', 'female', 'male', 'female', 'male'],
'Age': [22, 38, 26, 35, 35, np.nan, 54, 2, 14, 20, np.nan, 40],
'Fare': [7.25, 71.28, 7.92, 53.1, 8.05, 8.46, 51.86, 21.07, 30.07, 8.05, 26.0, 61.0],
'Embarked': ['S', 'C', 'S', 'S', 'S', 'Q', 'S', 'S', 'C', np.nan, 'S', 'C']})
print(df)
print("\nMissing values:\n", df.isnull().sum())Any question that says 'use the Iris dataset'
from sklearn.datasets import load_iris
iris = load_iris(as_frame=True)
df = iris.frame # 4 feature columns + 'target'
df['species'] = iris.target_names[iris.target]
print(df.head())
print(df['species'].value_counts())Simple / multiple linear regression
import pandas as pd
df = pd.DataFrame({
'Experience': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'Salary': [30000, 35000, 41000, 44000, 52000, 55000, 62000, 66000, 71000, 78000]})
print(df)
print("Correlation:", df['Experience'].corr(df['Salary']))If titanic.csv is provided, these cover the usual asks. The simulator has a practice titanic.csv with the same columns (synthetic rows).
Program 02 on Titanic
import pandas as pd
df = pd.read_csv('titanic.csv')
print("Before:\n", df.isnull().sum())
df['Age'] = df['Age'].fillna(df['Age'].median())
df['Embarked'] = df['Embarked'].fillna(df['Embarked'].mode()[0])
df = df.drop(columns=['Cabin']).drop_duplicates()
df['Sex'] = df['Sex'].map({'male': 0, 'female': 1})
print("\nAfter:\n", df.isnull().sum())
print(df.head())Programs 10 / 39 on Titanic
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('titanic.csv')
df.info()
print("\nSummary:\n", df.describe())
print("\nSurvival rate by sex:\n", df.groupby('Sex')['Survived'].mean())
print("\nSurvival rate by class:\n", df.groupby('Pclass')['Survived'].mean())
fig, ax = plt.subplots(1, 3, figsize=(15, 4))
sns.countplot(data=df, x='Pclass', hue='Survived', ax=ax[0]).set_title("Survival by Class")
sns.histplot(df['Age'].dropna(), bins=15, ax=ax[1]).set_title("Age Distribution")
sns.boxplot(data=df, x='Pclass', y='Fare', ax=ax[2]).set_title("Fare by Class")
plt.tight_layout()
plt.show()Programs 15 / 17 / 21 / 22 on Titanic
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, confusion_matrix
df = pd.read_csv('titanic.csv')
df['Age'] = df['Age'].fillna(df['Age'].median())
df['Sex'] = df['Sex'].map({'male': 0, 'female': 1})
X = df[['Pclass', 'Sex', 'Age', 'Fare']]
y = df['Survived']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
for name, model in [('Logistic Regression', LogisticRegression(max_iter=1000)),
('Decision Tree', DecisionTreeClassifier(max_depth=3, random_state=42))]:
y_pred = model.fit(X_train, y_train).predict(X_test)
print(f"{name:20s} Accuracy: {accuracy_score(y_test, y_pred):.4f}")
print(confusion_matrix(y_test, y_pred))Every import used across the 40 programs, grouped by module. Forgetting the module is the most common exam slip.
import matplotlib.pyplot as plt
import networkx as nx
import nltk
import numpy as np
import pandas as pd
import plotly.express as px
import seaborn as sns
import time
networkx.algorithms.community
greedy_modularity_communities, kernighan_lin_bisection
nltk.corpus
stopwords
nltk.stem
PorterStemmer
nltk.tokenize
word_tokenize
scipy
stats
scipy.cluster.hierarchy
dendrogram, fcluster, linkage
sklearn.cluster
AgglomerativeClustering, KMeans
sklearn.datasets
load_breast_cancer, load_digits, load_iris, load_wine, make_blobs, make_classification
sklearn.decomposition
PCA, TruncatedSVD
sklearn.ensemble
RandomForestClassifier
sklearn.feature_extraction.text
TfidfVectorizer
sklearn.linear_model
Lasso, LinearRegression, LogisticRegression, Ridge
sklearn.metrics
accuracy_score, classification_report, confusion_matrix, davies_bouldin_score, f1_score, mean_squared_error, precision_score, r2_score, recall_score, roc_auc_score, silhouette_score
sklearn.metrics.pairwise
cosine_similarity
sklearn.mixture
GaussianMixture
sklearn.model_selection
cross_val_score, train_test_split
sklearn.naive_bayes
GaussianNB
sklearn.neighbors
KNeighborsClassifier
sklearn.pipeline
make_pipeline
sklearn.preprocessing
StandardScaler
sklearn.svm
SVC
sklearn.tree
DecisionTreeClassifier, export_text
| Keys | Does |
|---|---|
| F5 | Run the whole file |
| F9 | Run the selected lines (or the current line) |
| Ctrl + Enter | Run the current cell (cells start with #%%) |
| Shift + Enter | Run the cell and move to the next one |
| Ctrl + . | Restart the kernel (clears all variables) |
| Ctrl + I | Show help for the name under the cursor, which works offline |
| Tab | Autocomplete: type sklearn.metrics. and press Tab to list the functions |
| Ctrl + 1 | Comment or uncomment the selected lines |