Skip to main content

NumPy and pandas: Preparing Data for Machine Learning

Updated 2 min readMarkdown
Part of seriesMLOPS
NumPy and pandas: Preparing Data for Machine Learning

Two Python libraries appear frequently in ML workflows: NumPy and pandas. They work together, but they solve different problems.

NumPy: numerical arrays

NumPy provides efficient multidimensional arrays and mathematical operations. It is useful for numerical computation and is commonly used underneath other ML libraries.

A model's prediction method may return a NumPy array:

predictions = model.predict(X_test)

The result might look like:

array([0, 1, 0, 0, 1])

pandas: labelled tabular data

pandas provides Series and DataFrames. A DataFrame is useful when data has rows, columns, and meaningful column names.

import pandas as pd

df = pd.read_csv("data/train.csv")
X = df.drop(columns=["is_fraud"])
y = df["is_fraud"]

Here, X contains model features and y contains the target the model should learn to predict.

Combining predictions with a DataFrame

Suppose the model returns a NumPy array. You can add it to a DataFrame as a new column:

predictions = model.predict(X_test)
results = X_test.copy()
results["prediction"] = predictions

Prefer bracket notation when creating columns. df["prediction"] is explicit and avoids conflicts with existing DataFrame attributes or methods.

A typical flow

CSV file
   ↓
pandas DataFrame
   ↓
Select features (X) and target (y)
   ↓
Train / evaluate model
   ↓
NumPy predictions
   ↓
pandas results DataFrame

Takeaway: think of pandas as the convenient table interface and NumPy as the numerical array foundation. Knowing how data moves between them makes ML code easier to understand.

No comments yet. Be the first to comment.