Machine-learning models need useful data before they need sophisticated algorithms. In practical projects, that data may come from a database, a CSV file, or several tables that must be combined. Pandas and SQL are two complementary ways to retrieve, organize, inspect, and transform that data.
Pandas is a Python library for analyzing and manipulating labeled tabular data. SQL (Structured Query Language) is a language for querying and working with relational databases. Pandas operates mainly on data available to the Python process; SQL lets a database engine filter, join, aggregate, and manage data where it is stored.
This article builds on Python for Artificial Intelligence and NumPy, Arrays, and Tensors. It focuses on data analysis, not on training a machine-learning model.
First intuition: two ways to ask questions about a dataset
Suppose a school stores student registrations in a database. You want to find students enrolled in an AI course and calculate their average quiz scores. SQL asks the database to retrieve and aggregate the relevant records. Pandas can analyze the resulting table in Python, where you may also visualize it or prepare it for modeling.
SELECT course, AVG(quiz_score) AS average_score
FROM enrollments
WHERE course = 'AI'
GROUP BY course;
import pandas as pd
records = pd.DataFrame({
"course": ["AI", "AI", "Databases"],
"quiz_score": [80, 90, 70]
})
print(records.loc[records["course"] == "AI", "quiz_score"].mean()) # 85.0
The database and DataFrame are not competing concepts. Both represent and transform tables; the best place to do the computation depends on data size, where the data is stored, and which tools you need afterward.
The role of tabular data in AI
Tabular data represents observations in rows and variables in columns. For example, an educational application could record learners, courses, and quiz results.
| learner_id | course | minutes_studied | quiz_score | completed |
|---|---|---|---|---|
| 101 | Python | 45 | 82 | True |
| 102 | Python | 30 | 74 | False |
| 103 | AI | 60 | 91 | True |
| 104 | AI | 25 | 68 | False |
In a prediction task, a row usually represents one training example, a feature is an input column, and the target is the quantity to predict. These roles depend on the problem: quiz_score might be a target in one experiment and a feature in another.
Tabular datasets are not necessarily clean. Values may be missing, identifiers may be duplicated, and records from different sources may disagree. Data analysis helps discover these problems before they contaminate downstream models.
1. Working with a Pandas DataFrame
A DataFrame is a two-dimensional labeled data structure. It has row labels (an index), column labels, and columns that may contain different data types. A Series is a one-dimensional labeled array and is commonly obtained by selecting one DataFrame column.
Install Pandas with:
python -m pip install pandas
Create a small reproducible dataset:
import pandas as pd
students = pd.DataFrame({
"learner_id": [101, 102, 103, 104],
"course": ["Python", "Python", "AI", "AI"],
"minutes_studied": [45, 30, 60, 25],
"quiz_score": [82, 74, 91, 68],
"completed": [True, False, True, False],
})
print(students.shape) # (4, 5)
print(students.columns.tolist()) # Column names
print(students["quiz_score"].mean()) # 78.75
The DataFrame’s shape is (number_of_rows, number_of_columns). Its index does not have to be the learner ID. By default, Pandas assigns a zero-based integer index.
Inspecting a dataset
Before calculating statistics or producing a model input, inspect the structure:
print(students.head())
print(students.info())
print(students.dtypes)
print(students.isna().sum())
print(students.describe(numeric_only=True))
head()displays the first rows;tail()displays the last rows.info()reports columns, data types, and non-null counts.dtypesshows the inferred storage type of each column.isna().sum()counts missing values by column.describe()gives basic descriptive statistics; it does not establish that data is valid.
For large datasets, inspect representative samples and distributions rather than assuming the first few rows tell the whole story.
2. Selecting, filtering, and sorting rows
A single column is selected with df["column"]. Several columns can be selected with a list:
subset = students[["learner_id", "quiz_score"]]
For label-based selection, use .loc; for position-based selection, use .iloc:
print(students.loc[0, "course"]) # Python
print(students.iloc[0, 3]) # 82
Use a Boolean condition to filter rows:
high_scores = students.loc[
students["quiz_score"] >= 80,
["learner_id", "course", "quiz_score"],
]
ordered = students.sort_values("quiz_score", ascending=False)
print(high_scores)
print(ordered)
Combine conditions with & (AND), | (OR), and ~ (NOT), placing each comparison inside parentheses:
selected = students.loc[
(students["course"] == "AI") & (students["quiz_score"] >= 80)
]
Python’s and and or operators are not substitutes for elementwise Boolean conditions on a Pandas Series.
3. Creating columns and summarizing groups
A derived column can represent a meaningful transformation of existing variables:
students["study_hours"] = students["minutes_studied"] / 60
students["passed"] = students["quiz_score"] >= 70
A group-by aggregation divides observations into groups, computes an aggregation in each group, and combines the results. This is useful when comparing categories or checking whether a dataset is imbalanced.
course_stats = students.groupby("course", as_index=False).agg(
learners=("learner_id", "count"),
mean_score=("quiz_score", "mean"),
completion_rate=("completed", "mean"),
)
print(course_stats)
For a Boolean column, the mean is the fraction of True entries among non-missing observations. Here, each course has a completion rate of 0.5, or 50%.
Important: Aggregates can conceal meaningful variation. A course-level average alone does not describe the distribution of individual scores or establish why two groups differ.
4. Missing values and data types
Missing values can appear as NaN, None, or Pandas’ nullable values depending on the column and data type. Missing does not necessarily mean zero.
records = pd.DataFrame({
"learner_id": [201, 202, 203],
"score": [80.0, None, 90.0],
"course": ["AI", "AI", None],
})
print(records.isna().sum())
# Inspect missing entries instead of deleting them automatically.
missing_scores = records.loc[records["score"].isna()]
print(missing_scores)
Common choices include investigating the source, excluding invalid records, introducing a missingness indicator, or filling missing values using a justified method. The correct choice depends on why values are missing and how the data will be used.
# Example only: median calculated on this illustrative dataset.
median_score = records["score"].median()
records["score_filled"] = records["score"].fillna(median_score)
For machine learning, fit imputation rules only on training data and apply the fitted rules to validation, test, and future data. Otherwise, evaluation data influences preprocessing and produces data leakage. This is explored further in Data Cleaning and Preprocessing and Data Splitting, Labeling, and Leakage.
A column may also have the wrong data type. For example, numeric measurements imported from CSV can contain text:
raw = pd.Series(["12", "15", "unknown"])
converted = pd.to_numeric(raw, errors="coerce")
print(converted.tolist()) # [12.0, 15.0, nan]
Converting invalid values to missing values can be useful, but record and investigate conversions rather than silently losing information.
5. Combining tables with joins
Real datasets are often normalized into multiple related tables. One table stores learner details; another stores activity or scores. A join combines related rows using a shared key.
learners = pd.DataFrame({
"learner_id": [101, 102, 103],
"region": ["North", "South", "North"],
})
scores = pd.DataFrame({
"learner_id": [101, 102, 103],
"quiz_score": [82, 74, 91],
})
combined = learners.merge(
scores,
on="learner_id",
how="inner",
validate="one_to_one",
)
print(combined)
| Join | Meaning |
|---|---|
| Inner join | Retain matching keys in both tables. |
| Left join | Retain all left-table rows, adding right-table values where matched. |
| Right join | Retain all right-table rows, adding left-table values where matched. |
| Full outer join | Retain keys from both sides, with missing values where no match exists. |
Check key uniqueness before joining. If the same key occurs multiple times in each table, a many-to-many join can multiply rows unexpectedly. Pandas’ validate argument helps enforce expected relationships. SQL joins require the same conceptual care.
6. SQL and relational databases
A relational database organizes data into relations, typically exposed as tables. Each table has columns and rows, and keys can identify rows and connect related tables. A primary key uniquely identifies a row within a table; a foreign key references related data in another table.
SQL lets the database evaluate a query and return a result set. Its main advantage is that a database engine can perform filtering, joins, sorting, and aggregations without moving every stored row into Python.
The following queries use common SQL syntax. Exact features and data types can vary across SQLite, PostgreSQL, MySQL, and other database systems.
Selecting and filtering
Assume a database table named study_sessions has columns learner_id, course, minutes_studied, and quiz_score.
SELECT learner_id, course, quiz_score
FROM study_sessions
WHERE quiz_score >= 80
ORDER BY quiz_score DESC;
SELECT chooses output expressions; FROM identifies the source; WHERE filters rows; and ORDER BY determines result order. Without an explicit ORDER BY, SQL results should not be assumed to have a stable order.
Grouping and aggregation
SELECT
course,
COUNT(*) AS session_count,
AVG(quiz_score) AS mean_score
FROM study_sessions
WHERE quiz_score IS NOT NULL
GROUP BY course
HAVING COUNT(*) >= 2;
WHERE filters input rows before grouping. HAVING filters groups after aggregation. COUNT(*) counts rows, while COUNT(column_name) counts rows with non-null values in that column.
Joining related tables
Suppose learners has learner_id and region, and study_sessions has learner_id and quiz_score:
SELECT
l.learner_id,
l.region,
s.quiz_score
FROM learners AS l
INNER JOIN study_sessions AS s
ON l.learner_id = s.learner_id;
A learner with multiple sessions legitimately appears multiple times. Before using the result for machine learning, decide whether each row should represent a learner, a session, or another unit of analysis.
NULL is not ordinary equality
SQL uses NULL to represent missing or unknown values. Use IS NULL or IS NOT NULL to test for them:
SELECT *
FROM study_sessions
WHERE quiz_score IS NULL;
The expression quiz_score = NULL does not provide the intended missing-value test because SQL’s treatment of unknown values uses three-valued logic.
7. A reproducible Python and SQLite example
SQLite is a lightweight relational database engine available through Python’s standard-library sqlite3 module. This makes it useful for learning SQL without configuring a separate database server.
The following complete example creates an in-memory database, inserts records, runs a parameterized query, and loads its result into Pandas:
import sqlite3
import pandas as pd
connection = sqlite3.connect(":memory:")
try:
connection.execute("""
CREATE TABLE study_sessions (
learner_id INTEGER,
course TEXT,
minutes_studied INTEGER,
quiz_score REAL
)
""")
rows = [
(101, "Python", 45, 82.0),
(102, "Python", 30, 74.0),
(103, "AI", 60, 91.0),
(104, "AI", 25, 68.0),
(105, "AI", 40, None),
]
connection.executemany(
"INSERT INTO study_sessions VALUES (?, ?, ?, ?)",
rows,
)
connection.commit()
threshold = 70.0
query = """
SELECT learner_id, course, minutes_studied, quiz_score
FROM study_sessions
WHERE quiz_score >= ?
ORDER BY quiz_score DESC
"""
result = pd.read_sql_query(query, connection, params=(threshold,))
result["study_hours"] = result["minutes_studied"] / 60
print(result[["learner_id", "course", "quiz_score", "study_hours"]])
finally:
connection.close()
The query returns three rows, for learners 103, 101, and 102, in descending score order. It excludes learner 104 because the score is below 70 and learner 105 because the score is missing.
The ? placeholder binds a value separately from SQL text. Parameterized queries are important when query values come from users or external systems because they prevent those values from being interpreted as SQL syntax. Do not construct SQL by directly concatenating untrusted values into query strings.
8. Translating common operations between SQL and Pandas
Both tools often express the same data operations with different syntax:
| Goal | SQL | Pandas |
|---|---|---|
| Select columns | SELECT a, b | df[["a", "b"]] |
| Filter records | WHERE score >= 70 | df.loc[df["score"] >= 70] |
| Sort records | ORDER BY score DESC | df.sort_values("score", ascending=False) |
| Group records | GROUP BY course | df.groupby("course") |
| Compute mean | AVG(score) | df["score"].mean() |
| Join tables | JOIN ... ON ... | left.merge(right, on="key") |
| Test missing | IS NULL | series.isna() |
These are conceptual correspondences, not guarantees of identical results. SQL and Pandas can differ in null handling, string collation, type conversion, grouping behavior, and ordering. Validate results when moving logic between them.
9. Choosing when to use SQL, Pandas, or both
SQL is often preferable when:
- Data already lives in a relational database.
- You need to select a small fraction of a large table.
- Joins and aggregates can be efficiently performed in the database.
- Shared data permissions and transaction rules must be enforced.
Pandas is often preferable when:
- Data fits comfortably into available memory.
- You need iterative exploratory analysis in Python.
- Transformations depend on Python’s analytical ecosystem.
- You want to inspect intermediate steps before model development.
Use both when SQL can extract and aggregate the relevant records, and Pandas can perform further inspection, feature preparation, or experimentation. Avoid downloading entire tables just to filter most rows away in Python.
For datasets larger than memory, consider database-side computation, chunked processing, or other suitable data-processing systems rather than assuming Pandas can load everything.
10. Data quality checks before machine learning
A successful SQL query or DataFrame operation does not guarantee valid model inputs. Before training, verify:
- Unit of observation: Does every row represent the intended entity, event, or time interval?
- Identifiers: Are keys unique where uniqueness is required?
- Completeness: Which values are missing, and why?
- Types and units: Are numbers, dates, categories, and measurement units correctly interpreted?
- Ranges: Are values plausible, and are extreme values legitimate observations or mistakes?
- Consistency: Do joins produce the expected row counts and relationships?
- Representativeness: Does the dataset reflect the population and conditions of intended use?
- Leakage: Does any variable reveal a future event or information unavailable when predictions will be made?
For example, a model intended to predict whether a learner will complete a course must not use the learner’s final completion status as an input feature. A perfectly accurate prediction obtained from information available only after the outcome is not a useful prediction system.
Reproducibility and privacy
Save the query logic, document transformations, record relevant dataset versions, and avoid manually altering results without a traceable reason. Do not include secrets, credentials, or sensitive personal data in notebooks or public repositories. Query only data you are authorized to access.
11. Common mistakes
- Treating row order as meaningful: Both database results and DataFrames may be reordered by transformations. Use explicit sorting when order matters.
- Confusing an index with a stable ID: A DataFrame’s default index is not a persistent learner or transaction identifier.
- Ignoring join cardinality: Duplicate join keys may multiply records and distort statistics.
- Assuming missing equals zero: Filling missing values without investigating the cause can introduce false patterns.
- Aggregating at the wrong level: Session-level results cannot automatically be interpreted as learner-level results.
- Calculating preprocessing statistics using all data: This can leak information from the test set into model development.
- Building SQL through string concatenation: Use bound parameters for untrusted values.
- Assuming a visually clean table is reliable: Data lineage, coverage, measurement quality, and bias require separate checks.
Check your understanding
- What is the difference between a Pandas
DataFrameand aSeries? - Why is a unique identifier often more reliable than a DataFrame’s default row index?
- How do
WHEREandHAVINGdiffer in SQL? - What happens if two tables contain multiple rows for the same join key?
- Why should a database filter large datasets before they are imported into Pandas?
- How could a dataset contain data leakage even if every row and column is valid?
Show worked answers
- A
DataFramehas two labeled dimensions (rows and columns); aSerieshas one labeled dimension. - The default row index may change after sorting, filtering, or combining tables, while a meaningful identifier can remain stable.
WHEREfilters rows before grouping;HAVINGfilters groups after aggregation.- The join may produce every matching pair, multiplying the number of resulting rows.
- It reduces network transfer and Python memory use, and lets the database use its query engine and indexes where applicable.
- A feature could reveal information known only after the target outcome, or preprocessing could have been fitted using evaluation data.
Related concepts
- AI Knowledge Map places data analysis in the wider AI learning sequence.
- Python for Artificial Intelligence introduces the language and programming practices used here.
- NumPy, Arrays, and Tensors explains numerical representations underlying many Pandas operations.
- AI Development Tools: Git, Jupyter, and APIs continues the practical programming foundations.
- Data Types and Data Collection for AI examines the sources and characteristics of data.
- Data Cleaning and Preprocessing covers missing values, duplicates, and transformation decisions more deeply.
- Data Splitting, Labeling, and Leakage explains how to protect model evaluation.
References and further reading
- Pandas user guide — core data manipulation and analysis concepts.
- Pandas: Getting started — DataFrame basics and introductory tutorials.
- Pandas: Merge, join, concatenate and compare — table combination behavior.
- Pandas: Working with missing data — missing-value representations and operations.
- SQLite SELECT documentation — SQL query clauses and their behavior.
- Python
sqlite3documentation — database connections and parameterized statements.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.