Python Essentials for Machine Learning
Python is the language of machine learning because its libraries make data easy to handle. NumPy gives you fast arrays for numbers, pandas gives you DataFrames for tables, and matplotlib lets you see the data. Most ML code is just moving data between these three.
NumPy arrays look like lists but are faster and support math on whole columns at once. A list [1,2,3] times 2 gives [1,2,3,1,2,3], while a NumPy array [1,2,3] times 2 gives [2,4,6]. This difference matters when you scale features.
Pandas DataFrames feel like spreadsheets. You will spend more time cleaning DataFrames than training models. The most common error, SettingWithCopyWarning, appears when you chain filters and assignments, and it means your change may not have saved.
NumPy vs lists
Use NumPy for numbers and pandas for tables. Lists are for general Python, arrays are for ML math. When you see X and y in tutorials, X is usually a NumPy array or DataFrame, y is the target column.
import numpy as np
import pandas as pd
a = np.array([1,2,3])
print(a * 2) # [2 4 6]
df = pd.DataFrame({"age":[25,30], "price":[200,250]})
print(df.head())
The copy warning
Never do df[df.age > 30]["price"] = 0. This chained assignment may write to a copy, not the original. Use loc: df.loc[df.age > 30, "price"] = 0. This GitHub pandas issue is the top ML beginner trap.
# Bad: df[df.age>30]["price"]=0 # may not save
# Good:
df.loc[df.age>30, "price"] = 0
Syntax
import numpy as np
import pandas as pd
df = pd.read_csv("housing.csv")
X = df[["bedrooms","sqft"]].values
y = df["price"].values
print(X.shape, y.shape)
SettingWithCopyWarning is not a warning to ignore
Pandas shows this when you do df[filter]["col"]=value. Your change may be lost. GitHub pandas #14209 has 200+ comments from ML beginners. Always use loc or copy explicitly.
df.loc[mask, "col"] = value # safe
# or df_copy = df[mask].copy()
Good to know
- NumPy for numbers, pandas for tables, matplotlib for plots.
- X is usually 2D (samples × features), y is 1D (target).
- Use loc for assignments to avoid SettingWithCopyWarning.