The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
This data science cheat sheet is a workflow-first reference for common Python, SQL, statistics, visualization, and machine-learning tasks. It is intended for learners, analysts, and practitioners who want a concise reminder of what to do next—and of the mistakes that can invalidate an answer. Updated September 23, 2026. A cheat sheet helps with lookup; it does not replace deeper study of statistical reasoning, data quality, or model validation.
There is no single official data science cheat sheet. The useful reference is the one that connects commands to decisions: define the question, inspect and prepare the data, analyze it, validate conclusions, and communicate or deploy the result.
Data science workflow at a glance
- Define the decision or question. Identify who will use the result and what would change based on it.
- Acquire and understand the data. Establish its source, time period, unit of observation, and limitations.
- Inspect and clean. Check types, missing values, duplicates, ranges, and keys.
- Explore and visualize. Describe distributions and compare relevant groups before choosing a model.
- Split appropriately. Keep related people or devices together and respect time order where needed.
- Preprocess and model. Fit transformations on training data only; compare sensible baselines.
- Evaluate and interpret. Choose metrics that reflect the decision, check subgroups, and avoid test-set contamination.
- Report, deploy, or revisit. Document assumptions, provenance, limitations, and how performance may change.
Data science combines domain understanding, data management, programming, statistics, visualization, and sometimes machine learning and deployment. Data analysis often describes or diagnoses; machine learning learns patterns from data; data engineering builds data systems; business intelligence supports recurring reporting. These activities overlap, and not every data-science project needs machine learning.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Set up a working environment
For a local Python project, create an isolated environment and install a practical starter stack:
#1 Best Overall
python -m venv .venv
# macOS/Linux
source .venv/bin/activate
# Windows PowerShell
.venvScriptsActivate.ps1
python -m pip install --upgrade pip
python -m pip install numpy pandas scipy scikit-learn matplotlib seaborn jupyter
jupyter lab
Installation details can differ by operating system, Python distribution, and package resolver. Consult the current official installation documentation when a command fails, and record your Python and package versions for reproducibility.
For a browser-based start, Google Colab provides hosted Jupyter notebooks without local setup. Its free resources, including possible GPU or TPU access, are limited and variable rather than guaranteed. It suits tutorials and small experiments, but is a poor fit for sensitive data, guaranteed compute, or tightly controlled production environments. The Jupyter documentation explains the notebook ecosystem; notebooks combine executable code, prose, and visualizations, but can hide state when cells are run out of order.
Python essentials
# Values and collections
x = 10
name = "Ada"
values = [1, 2, 3]
record = {"name": "Ada", "score": 95}
# Condition, loop, function
if x > 5:
print("large")
for value in values:
print(value)
def add(a, b):
return a + b
# Comprehension
squares = [n * n for n in values if n > 1]
# Handle a specific expected failure
try:
result = 10 / 0
except ZeroDivisionError:
result = None
- Python sequences use zero-based indexing: the first item is at index
0. Noneis Python’s null-like singleton; usevalue is Noneto test it. NumPy’snp.nanis a floating-point missing-value marker and behaves differently in comparisons.- Lists and dictionaries are mutable; integers, strings, and tuples are immutable. Mutating a shared list can affect other references to it.
- Use import aliases conventionally:
import numpy as npandimport pandas as pd. - Read the last lines of a traceback first, then trace the failing value and type. Catch specific exceptions rather than hiding every error with a broad
except. - For numerical and tabular work, vectorized operations are often clearer and more efficient than Python loops, though the benefit depends on the operation and data.
NumPy essentials
NumPy supplies array-oriented numerical operations used throughout Python’s scientific-computing ecosystem.
import numpy as np
a = np.array([1, 2, 3])
matrix = np.array([[1, 2], [3, 4]])
a.shape # dimensions and lengths
a.ndim # number of dimensions
a.dtype # element type
column = a.reshape(3, 1)
np.mean(a)
np.std(a)
np.where(a > 1, a, 0)
rng = np.random.default_rng(42)
sample = rng.normal(size=5)
- Shape and axes: a matrix with shape
(rows, columns)has axis 0 for rows and axis 1 for columns. For example,matrix.mean(axis=0)computes one mean per column. - Broadcasting: NumPy can apply compatible shapes without manually repeating values, such as subtracting a vector of column means from every row. Check shapes when results look unexpectedly expanded.
- Boolean masks:
a[a > 1]selects matching values. A mask’s shape must be compatible with the array being indexed. - Missing values:
np.nanis not equal to itself; use functions such asnp.isnanor NaN-aware aggregations when appropriate. - Randomness: a seeded generator makes a sequence reproducible in a controlled environment; record the seed and software versions rather than assuming every library’s random behavior is identical.
- Views and copies: slicing may return a view sharing underlying data, while other operations create copies. If mutation matters, make an explicit copy and verify behavior.
pandas cheat sheet
Use pandas for labeled tabular data. Its official documentation is the reference for version-specific behavior.
Rank #2
Read and inspect
import pandas as pd
df = pd.read_csv("data.csv")
df.head()
df.shape # property, not a function
df.info()
df.describe(include="all")
df.dtypes
df.isna().sum()
df.nunique()
Select and filter
df["sales"]
df[["sales", "region"]]
df.loc[df["sales"] > 1000, ["region", "sales"]]
df.iloc[:5, :3]
df.query("sales > 1000 and region == 'West'")
loc selects by labels or Boolean conditions; iloc selects by integer position. Confirm that a filter uses the intended units and that null values do not silently alter the result.
Clean and validate
df = df.drop_duplicates()
df["age"] = pd.to_numeric(df["age"], errors="coerce")
df["date"] = pd.to_datetime(df["date"], errors="coerce")
df["income"] = df["income"].fillna(df["income"].median())
df = df.dropna(subset=["target"])
df = df.rename(columns={"old_name": "new_name"})
These are operations, not automatic judgments about good data. Check how many values became missing during coercion; verify date formats, time zones, categories, and identifier uniqueness. dropna() can remove substantial data. Imputation statistics must be learned from training data only when building a predictive model.
Group, join, reshape, and export
summary = (
df.groupby("region", as_index=False)
.agg(
total_sales=("sales", "sum"),
average_sales=("sales", "mean"),
orders=("order_id", "nunique")
)
)
joined = customers.merge(
orders, on="customer_id", how="left", validate="one_to_many"
)
combined = pd.concat([df_2025, df_2026], ignore_index=True)
wide = df.pivot_table(
index="region", columns="month", values="sales", aggfunc="sum"
)
long = wide.reset_index().melt(
id_vars="region", var_name="month", value_name="sales"
)
df.to_csv("cleaned.csv", index=False)
df.to_excel("cleaned.xlsx", index=False)
df.to_parquet("cleaned.parquet", index=False)
A join may increase row counts when keys are duplicated. Check key uniqueness and compare row counts and totals before and after; set validate= to the relationship you expect. Prefer vectorized expressions and built-in aggregation over apply() where practical. Correlation in an exploratory table is not evidence of causation.
SQL essentials
These examples use broadly familiar SQL patterns, not a guarantee of identical syntax across database engines. Date literals, string functions, and null handling can differ; consult the documentation for your database. SQL results have no guaranteed order without ORDER BY.
Rank #3
SELECT
region,
COUNT(*) AS orders,
SUM(sales) AS total_sales,
AVG(sales) AS average_sales
FROM orders
WHERE order_date >= DATE '2026-01-01'
GROUP BY region
HAVING SUM(sales) > 10000
ORDER BY total_sales DESC;
WHERE filters rows before grouping; HAVING filters groups after aggregation.
SELECT c.customer_id, c.segment, o.order_id, o.sales
FROM customers AS c
LEFT JOIN orders AS o
ON c.customer_id = o.customer_id;
An inner join drops unmatched rows; a left join preserves rows from its left table. Duplicate keys on both sides can multiply results, so inspect cardinality before joining.
SELECT customer_id, order_date, sales,
SUM(sales) OVER (
PARTITION BY customer_id
ORDER BY order_date
) AS running_sales
FROM orders;
For nulls, write IS NULL or IS NOT NULL, not = NULL. A window function can calculate a value across related rows without collapsing them like a grouped aggregate.
Free tools Windows power users keep installed
One-click scans. No signup required.
Exploratory data analysis checklist
- Confirm the unit represented by each row and whether it is unique.
- Identify the outcome or target if the question has one.
- Check row and column counts, types, and data provenance.
- Measure missingness and inspect whether it varies by group or time.
- Find duplicate records and duplicate identifiers; determine whether they are errors or valid repeated events.
- Inspect unique values, category balance, and impossible ranges.
- Examine distributions, outliers, and subgroup differences.
- Check time coverage, delayed outcomes, and any information that would not have been available at prediction time.
- Record assumptions, exclusions, and transformations.
df.describe()
df["category"].value_counts(dropna=False)
df.select_dtypes("number").corr()
df.isna().mean().sort_values(ascending=False)
Summary statistics can conceal skew, multiple modes, outliers, data-entry mistakes, or Simpson’s paradox, where a pattern within groups differs from the aggregate. Treat an unusual value as a question to investigate, not an automatic deletion candidate.
Rank #4
Visualization: choose the chart for the question
| Question | Useful starting chart |
|---|---|
| How is a numeric variable distributed? | Histogram, density plot, or box plot |
| How do two numeric variables relate? | Scatter plot |
| How do categories compare? | Sorted bar chart |
| How does a measure change over time? | Line chart |
| How do groups differ in distribution? | Box plot or violin plot |
| Where are values missing? | Missingness bar chart or matrix |
| How do variables correlate? | Correlation heatmap, interpreted cautiously |
import matplotlib.pyplot as plt
import seaborn as sns
sns.histplot(data=df, x="sales", bins=30)
plt.xlabel("Sales")
plt.ylabel("Count")
plt.title("Sales distribution")
plt.show()
Label axes and units, use color consistently, and show sample size when it matters. Start bar-chart magnitude axes at zero; avoid unnecessary 3D effects and visual encodings with too many dimensions. Describe whether a visible pattern is merely descriptive or supported by an inferential design.
Statistics and probability: interpretation before formula
- Mean and median: measures of center; the median is less affected by extreme values.
- Variance and standard deviation: measures of spread in squared units and original units, respectively. Sample and population formulas differ.
- Percentiles and interquartile range: locate observations in a distribution; IQR is the 75th percentile minus the 25th.
- Covariance and correlation: describe how variables vary together. Correlation is scaled, but neither measure establishes causation.
- Conditional probability: probability of an event given another event. Independence means conditioning on one does not change the probability of the other.
- Bayes’ theorem: updates a prior probability using evidence and a likelihood; base rates matter.
- Expected value and variance: summarize a random variable’s long-run average and spread.
- Common distributions: Bernoulli for a binary outcome, binomial for counts of successes in fixed trials, normal for a symmetric continuous model, Poisson for event counts under assumptions, and exponential for waiting times under a constant-rate model.
Inference uses sample data to reason about a population. A confidence interval describes the long-run behavior of a procedure under its assumptions; it is not a guarantee that a particular interval contains a fixed parameter. A p-value is not the probability that the null hypothesis is true. Statistical significance is not the same as a practically important effect. Report effect sizes and uncertainty, account for multiple comparisons, and pre-specify analyses where possible. A/B tests need valid randomization and a suitable analysis plan; optional stopping and repeated testing can inflate false-positive risk.
Preprocessing without leakage
For predictive work, separate the target, split the data, then fit transformations on training data only. Apply those fitted transformations to validation and test data. Do not let test-set information influence imputation, scaling, feature selection, or tuning.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutefrom sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
X = df.drop(columns="target")
y = df["target"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
numeric_features = ["age", "income"]
categorical_features = ["region", "segment"]
numeric_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler())
])
categorical_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore"))
])
preprocessor = ColumnTransformer([
("numeric", numeric_pipeline, numeric_features),
("categorical", categorical_pipeline, categorical_features)
])
In a complete workflow, fit the preprocessor and estimator together in a pipeline, and use that same pipeline for validation and prediction. Scaling matters for many distance- or gradient-sensitive models; tree models often do not require it. One-hot encoding suits many nominal categories, but not every data type or every model. Do not ordinal-encode categories just because they can be alphabetized. Dates, text, images, and high-cardinality identifiers need deliberate treatment. Never include the target among the features being transformed.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Choose a model by task, not by slogan
| Task | Reasonable starting points |
|---|---|
| Binary classification | Logistic regression, random forest, gradient boosting |
| Multiclass classification | Logistic regression, tree ensembles, gradient boosting |
| Regression | Linear or regularized linear models, random forest, gradient boosting |
| Clustering | k-means, hierarchical clustering, density-based methods |
| Dimensionality reduction | PCA, feature selection, non-negative matrix factorization |
| Text classification | Linear models with TF-IDF, then specialized language models if justified |
| Time series | Time-aware baselines, statistical forecasting, feature-based models |
Start with a baseline that reflects the task. For example, a majority-class baseline can reveal whether a classifier adds value beyond class prevalence:
from sklearn.dummy import DummyClassifier
baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(X_train, y_train)
There is no universally best algorithm. Consider interpretability, predictive performance, calibration, training and inference cost, robustness, and expected distribution shift. The scikit-learn documentation covers classification, regression, clustering, dimensionality reduction, preprocessing, and model selection. Its stable release was listed as 1.9.0 in June 2026; examples can still need adjustment as libraries change.
Evaluate with a metric that matches the decision
Classification
- Accuracy: fraction correct; can be misleading when classes are imbalanced or error costs differ.
- Precision: among predicted positives, the fraction that are positive.
- Recall (sensitivity): among actual positives, the fraction found.
- Specificity: among actual negatives, the fraction correctly rejected.
- F1: harmonic mean of precision and recall; it does not account for true negatives.
- ROC AUC: ranking performance across thresholds; it does not choose an operating threshold.
- PR AUC: precision-recall performance, often useful when positives are rare.
- Log loss and calibration: assess probability quality and whether predicted probabilities align with observed frequencies.
from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score
pred = model.predict(X_test)
prob = model.predict_proba(X_test)[:, 1]
print(confusion_matrix(y_test, pred))
print(classification_report(y_test, pred))
print(roc_auc_score(y_test, prob))
Choose thresholds using the costs of false positives and false negatives, not by habit. For imbalanced classes, report the confusion matrix and suitable precision-recall measures rather than accuracy alone.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Regression and time series
- MAE: average absolute error, in target units.
- MSE: squares errors and penalizes large misses more.
- RMSE: square-rooted MSE, in target units.
- R²: a variance-explanation measure with limitations; it is not a universal measure of model quality.
- MAPE: unstable around zero and unsuitable for some signed or low-valued targets.
For time series, validate in time order. Do not randomly shuffle future observations into training data unless that genuinely matches the intended use.
Cross-validation and tuning
from sklearn.model_selection import cross_validate, StratifiedKFold
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_validate(
model, X_train, y_train, cv=cv,
scoring=["accuracy", "precision", "recall", "roc_auc"]
)
Use stratified folds for many classification problems to preserve class proportions. Use grouped folds when multiple rows belong to the same person, patient, device, or account. Use time-series splits for temporal prediction. Nested cross-validation can estimate performance more rigorously when model selection itself is part of the evaluation. Tune against training/validation data under a fixed protocol, not repeatedly against the final test set.
Interpretability, fairness, and responsible use
Feature importance is not causal importance. Permutation importance, partial dependence, accumulated local effects, or SHAP-style methods can help describe model behavior, but an explanation is not proof of a causal reason for an individual outcome. Check performance across relevant subgroups; investigate missing-data and measurement bias, proxy variables, and data provenance. Consider privacy and security, document intended use and limitations, and retain human review for high-impact decisions. Predictive accuracy alone does not establish that a system is fair, safe, or ready to deploy.
Reproducibility checklist
import numpy as np
rng = np.random.default_rng(42)
- Record Python and package versions, data source, and snapshot date.
- Keep raw data immutable; document exclusions and transformations.
- Save the fitted preprocessing and model pipeline together.
- Use meaningful random seeds and capture the validation design.
- Separate exploratory notebooks from production code; test transformations.
- Restart the notebook kernel and run every cell from top to bottom before sharing.
- Export a clean report or reproducible script and state the analysis limitations.
Common failure modes and quick checks
| Symptom or mistake | What to check |
|---|---|
| Suspiciously strong test score | Look for leakage, post-outcome features, preprocessing fit on all data, or feature selection using the test set. |
| Aggregates inflate after a merge | Check key uniqueness, join cardinality, row counts, and totals; use pandas validate= to assert the expected relationship. |
| High accuracy but poor usefulness | Check class prevalence, confusion matrix, precision, recall, threshold, and error costs. |
| Training score much better than validation | Investigate overfitting, leakage, split design, and time-period shift. |
| Missing values replaced mechanically | Determine whether missingness is random, related to observed fields, or itself meaningful; choose imputation based on context. |
| Outliers removed automatically | Decide whether each is an error, legitimate rare event, measurement problem, or important population. |
| Notebook gives different results when shared | Restart the kernel, run all cells in order, and remove hidden-state dependencies. |
Authoritative references
- NumPy documentation and pandas documentation.
- scikit-learn documentation for preprocessing, estimators, validation, and metrics.
- Jupyter documentation and Colab FAQ for notebook environments.
Use a layered reference rather than trying to cram every topic into one poster: keep a one-page workflow and metrics sheet, then separate Python/pandas, SQL, statistics, machine learning, and notebook checklists. Always check the relevant library or database documentation for syntax that may vary by version or engine.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsQuick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

