Quick reference · Python
Python cheat sheet
The symbols that trip people up, then the calls you will use again and again. Skim it, find your line, get back to the lesson.
Try the symbols
Change a number and run it again. One equals sign stores a value; two ask a question.
Live Python
= stores, == asks
Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.
Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.
Symbols that look alike
Most early Python confusion is about one character. Read the symbol aloud as the words in the middle column.
| Symbol and example | Say it as | Common slip |
|---|---|---|
price = 250 | Store 250 under the name price. One equals sign GIVES a value. | Writing 250 = price (the name goes on the left). |
price == 250 | Is price equal to 250? The answer is True or False. | Writing if price = 250: gives a SyntaxError. Use ==. |
price != 250 | Is price different from 250? | |
price >= 250 | Is price at least 250? Also <, >, <=. | Writing => instead of >=. |
total += 5 | Add 5 to total and store it back. Same as total = total + 5. | |
a and b / a or b / not a | Combine single True/False answers. | Using and between two pandas masks. Use & and | there. |
(x > 0) & (y > 0) | Both conditions, for whole NumPy or pandas columns at once. | Forgetting the brackets around each condition. |
x in [1, 2, 3] | Is x one of these? | |
2 ** 3 | Two to the power 3 = 8. Not ^, which means something else. | Using ^ for powers. |
7 // 2 and 7 % 2 | Whole-number division (3) and the remainder (1). | |
A @ B | Matrix multiplication (NumPy). | Using * for matrices. * multiplies entry by entry. |
items[0], items[1:3], items[-1] | First item, items 1 and 2 (the end is left out), last item. Counting starts at 0. | Expecting items[1:3] to include index 3. |
def f(x): ... if x: ... for i in r: | A colon opens an indented block. | Forgetting the colon or the indentation. |
df.shape, df.head() | A dot reaches inside an object: .shape is a fact, .head() is an action (note the brackets). | Adding () after a fact like .shape. |
{'a': 1}, [1, 2], (1, 2) | A dictionary (look up by key), a list (ordered, changeable), a tuple (ordered, fixed). | |
f"{rate:.1%}" | Put a value inside text; .1% shows 0.265 as 26.5%. | |
# note | A comment. Python ignores it. |
Python essentials
| Code | What it does | Tip |
|---|---|---|
print(x) | Show a value. | |
type(x), len(items) | What kind of thing, and how many. | |
int("3"), float("2.5"), str(7) | Convert between number and text. | Numbers read from files often arrive as text. |
for item in items: | Repeat for each item. | |
for i, item in enumerate(items): | Loop with a counter. | |
for a, b in zip(xs, ys): | Walk two lists together. | |
if x > 0: ... elif x == 0: ... else: ... | Choose a path. | |
def mean(xs): return sum(xs) / len(xs) | Define a reusable function. | return hands back the answer; print only shows it. |
[x * 2 for x in xs] | Build a new list from an old one. | |
[x for x in xs if x > 0] | Keep only items that pass a test. | |
d = {"a": 1}; d["a"]; d.get("z", 0) | Dictionary: look up a key, or use a default. | .get avoids a KeyError. |
sum(xs), min(xs), max(xs), sorted(xs) | Built-in summaries. | |
import numpy as np | Load a library under a short name. | Put imports at the top. |
NumPy
| Code | What it does | Tip |
|---|---|---|
a = np.array([[1, 2], [3, 4]]) | Make an array from lists. | |
a.shape, a.ndim, a.size, a.dtype | Rows × columns, number of axes, number of cells, kind of number. | Shape (3, 2) means 3 rows, 2 columns. |
np.zeros((2, 3)), np.ones(3), np.arange(5) | Arrays of zeros, ones, 0 to 4. | |
np.linspace(0, 1, 5) | Five evenly spaced numbers from 0 to 1, both included. | |
a.reshape(2, 3), a.T | Regroup the same cells; transpose. | Reshape keeps the order, it does not sort. |
a[0], a[:, 1], a[1:, :2] | A row, a column, a block. | [rows, columns]. |
a[a > 2] | Keep only entries that pass the test (a boolean mask). | |
a.sum(axis=0), a.mean(axis=1) | Sum down each column; average across each row. | axis=0 collapses rows. axis=1 collapses columns. |
a * 2, a + b | Entry by entry arithmetic. | Shapes must match or broadcast. |
a @ b, np.dot(u, v) | Matrix product; dot product. | |
np.where(a > 0, 1, 0) | Pick one value or the other, entry by entry. | |
np.linalg.norm(v) | Length of a vector. | |
rng = np.random.default_rng(0); rng.normal(size=5) | Repeatable random numbers. | Always set a seed when you want the same answer twice. |
pandas
| Code | What it does | Tip |
|---|---|---|
df = pd.read_csv("data/file.csv") | Load a table. | |
df.shape, df.head(), df.info(), df.describe() | Size, first rows, column types and gaps, summary numbers. | Run these first, every time. |
df["price"], df[["price", "area"]] | One column (a Series), several columns (a table). | Double brackets give a table. |
df.loc[df["price"] > 200, "area"] | Rows that pass a test, one column, by name. | loc uses names, iloc uses positions. |
df.iloc[0:5, 0:2] | By position: first 5 rows, first 2 columns. | |
df[(df["a"] > 1) & (df["b"] == "x")] | Filter on two conditions. | Use & and |, with brackets. |
df.isna().sum() | Count missing values per column. | |
df.fillna(0), df.dropna() | Fill gaps; drop rows with gaps. | Learn fill values from training rows only. |
df.groupby("city")["price"].mean() | Average price per city. | Also .agg(["mean", "count"]). |
df["city"].value_counts() | How often each value appears. | |
df.sort_values("price", ascending=False) | Sort the table. | |
pd.merge(a, b, on="id", how="left") | Join two tables on a shared column. | how="left" keeps every row of a. |
df["ratio"] = df["a"] / df["b"] | Add a new column. | |
pd.get_dummies(df, columns=["city"]) | Turn words into 0/1 columns. | |
pd.to_numeric(s, errors="coerce") | Turn text into numbers; bad entries become NaN. |
Charts with matplotlib
| Code | What it does | Tip |
|---|---|---|
fig, ax = plt.subplots() | Create one chart. | Add figsize=(6, 4) to set the size. |
ax.plot(x, y) | A line. | Good for change over an ordered x. |
ax.scatter(x, y) | Points. | Good for two numbers per row. |
ax.hist(values, bins=20) | How values are spread. | |
ax.bar(names, heights) | Compare categories. | Start the axis at zero. |
ax.set_xlabel("Area"), ax.set_ylabel("Price"), ax.set_title("...") | Say what the axes mean. | Include units. |
ax.legend() | Label several series. | Give each plot a label=. |
plt.show() | Display the chart. | |
fig.savefig("chart.png", dpi=150) | Save it. |
Preparing data
| Code | What it does | Tip |
|---|---|---|
train, test = train_test_split(df, test_size=0.2, random_state=42) | Hold some rows back for the final check. | Add stratify=y to keep class shares equal. |
imp = SimpleImputer(strategy="median") | Fill gaps with the typical value. | |
scaler = StandardScaler() | Put columns on a common scale (mean 0, spread 1). | |
enc = OneHotEncoder(handle_unknown="ignore") | Words to 0/1 columns. | |
scaler.fit(X_train); scaler.transform(X_test) | Learn from train, apply to test. | fit on train only. Fitting on test leaks the answer. |
ColumnTransformer([("num", scaler, numeric), ("cat", enc, words)]) | Different treatment for number and word columns. | |
make_pipeline(prep, model) | Chain preparation and model so they travel together. | Prevents leakage in cross-validation. |
scikit-learn
| Code | What it does | Tip |
|---|---|---|
model = LinearRegression() | Create a model. Nothing is learned yet. | |
model.fit(X_train, y_train) | Learn from the training rows. | |
model.predict(X_valid) | Guess answers for new rows. | |
model.predict_proba(X_valid)[:, 1] | Chance of class 1 (classifiers). | |
mean_absolute_error(y, pred) | Average miss, in the target's units. | |
r2_score(y, pred) | Share of the ups and downs explained. | 0 = nothing, 1 = everything. |
accuracy_score(y, guess) | Share right. | Misleading when one class is rare. |
precision_score, recall_score, f1_score | Flagged-and-right, caught, and a blend of both. | |
roc_auc_score(y, prob) | How well scores rank positives above negatives. | 0.5 = coin flip. |
confusion_matrix(y, guess) | Counts of each kind of right and wrong. | |
cross_val_score(model, X, y, cv=5) | Average the score over 5 different splits. | |
GridSearchCV(model, {"alpha": [0.1, 1, 10]}, cv=5) | Try settings and keep the best. | Keep the test set out of it. |