Introduction to Pandas

Published by Brayan K

Pandas is an open-source Python library for working with tabular data — the rows and columns you see in a spreadsheet — giving you fast, expressive tools to load, clean, analyse, and save real-world datasets.

Part of the free Pandas course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Begin with a question you can answer from a table

Suppose a small stock count has one row per item and one column for its quantity. Before writing code, decide what a row means, which column is numeric and which result would answer the question. Here the question is how many units the three rows contain.

import pandas as pd

# Every row describes one item in this single stock count.
stock = pd.DataFrame({
    "item": ["pen", "book", "folder"],
    "quantity": [4, 2, 3],
})
print(stock.shape)
print(stock.columns.tolist())
# The selected quantity column contains numbers, so sum adds them.
print(int(stock["quantity"].sum()))

# ✅ Expected output:
# (3, 2)
# ['item', 'quantity']
# 9

The result is a two-dimensional DataFrame. Its shape reports rows first and columns second; selecting one named column produces a Series. The DataFrame: Rows and Columns owns the table model and The Series: Pandas' 1-D Building Block owns a labelled column.

Pandas helps express repeatable data operations in Python. It does not decide whether the source observations are true, whether a row has been duplicated, or whether a missing value should count as zero. Those are questions you must resolve from the data’s meaning.

An import creates a name in the current Python process

Pandas is an installed Python package, not a separate programming language and not part of Python’s standard library. In a local terminal, use python -m pip install pandas with the same interpreter that runs your script. A notebook’s selected kernel can be a different environment. The site editor supplies its own browser runtime; typing a terminal installation command into a Python code block is a different operation.

import pandas as pd

print(pd.__name__)
print(callable(pd.DataFrame))

# ✅ Expected output:
# pandas
# True
import pandas as pd

pandas.DataFrame({"quantity": [1, 2]})

# ✅ Expected error:
# NameError: name 'pandas' is not defined

Keep import pandas as pd at the start of each complete standalone example. Restarting a notebook kernel removes names created by earlier cells; a script should not depend on a cell you happened to run yesterday. Avoid naming your own file pandas.py, because a local module can shadow the installed package. Installation and kernel selection are environment tasks; the examples here do not print a machine-specific path or installed version.

A numeric-looking value may still be text

import pandas as pd

text = pd.Series(["4", "2", "3"], dtype="object")
numbers = pd.Series([4, 2, 3], dtype="int64")
print(text.sum())
print(int(numbers.sum()))
print(str(text.dtype), str(numbers.dtype))

# ✅ Expected output:
# 423
# 9
# object int64

The text column concatenates strings; the numeric column adds numbers. The values and their dtype both matter. Defaults for inferred types can differ between Pandas versions, so the examples state the type when it is part of the lesson’s claim. Data Types & astype owns conversion and validation; this introduction only shows why the distinction matters.

import pandas as pd

quantity = pd.Series([4, None, 3], dtype="Int64")
print(len(quantity), int(quantity.count()))
print(quantity.isna().tolist())
print(int(quantity.sum()))

# ✅ Expected output:
# 3 2
# [False, True, False]
# 7

There are three rows but only two known quantities. The displayed total comes from the known values; it does not prove that the unknown quantity was zero. Handling Missing Data (NaN, fillna, dropna) owns the policy for missing observations.

A repeatable program still needs a clear input boundary

import pandas as pd

def known_total(values):
    quantities = pd.Series(values, dtype="Int64")
    return int(quantities.count()), int(quantities.sum())

first = known_total([2, 5, None])
second = known_total([2, 5, None])
print(first)
print(first == second)

# ✅ Expected output:
# (2, 7)
# True

Keeping the input fixed makes this result repeatable. A real analysis should also record how data was collected and how it was cleaned. Re-running identical code against a changed file can legitimately produce a different answer. Reading & Writing Data (CSV, Excel, JSON) owns loading and saving formats.

A DataFrame usually occupies memory in the current process. File size alone is not a reliable estimate of memory use, and using Pandas does not automatically make a dataset fit in RAM or make every operation faster than a spreadsheet or a database. Choose a tool for the workload and measure when scale matters. Pandas can also use extension-backed columns; it is not accurate to describe every column as an ordinary NumPy array.

Guided exercise: identify the shape before calculating

Use the literal hints to build the table, select the numeric column and calculate its total.

import pandas as pd

# 👉 replace ___ with DataFrame
stock = pd.___({"item": ["card", "clip"], "quantity": [6, 4]})
# 👉 replace ___ with shape
print(stock.___)
# 👉 replace ___ with sum
print(int(stock["quantity"].___()))

# ✅ Expected output:
# (2, 2)
# 10

Build brief: report known observations without inventing a missing value

Build a table with item values pen, book and folder and quantities 4, missing and 3. Give quantity the nullable Int64 dtype. Print the table’s shape, item names, number of known quantities, known total and whether any quantity is missing. Do not fill the missing value or claim that the known total describes all stock.

import pandas as pd

stock = pd.DataFrame({
    "item": ["pen", "book", "folder"],
    "quantity": pd.Series([4, None, 3], dtype="Int64"),
})
print(stock.shape)
print(stock["item"].tolist())
print(int(stock["quantity"].count()))
print(int(stock["quantity"].sum()))
print(bool(stock["quantity"].isna().any()))

# ✅ Expected output:
# (3, 2)
# ['pen', 'book', 'folder']
# 2
# 7
# True

Check the report against the input one row at a time. There must be three items, two known quantities and a visible missingness flag. This small workflow establishes the habit used throughout the course: state the question, inspect the representation, perform a specific operation and keep the result’s limits visible.

Practice quiz

What does this program print? import pandas as pd frame = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) print(frame.shape)

  • (3, 2)
  • (2, 3)
  • (3, 3)
  • 6

Answer: (3, 2). Shape is rows, then columns.

What does this program print? import pandas as pd print(pd.__name__)

  • pd
  • pandas
  • DataFrame
  • numpy

Answer: pandas. The alias refers to the imported pandas module.

What does this program print? import pandas as pd print(pd.Series(["2", "3"], dtype="object").sum())

  • 5
  • [2, 3]
  • 23
  • TypeError

Answer: 23. The selected object values are strings, so sum concatenates them here.

What does this program print? import pandas as pd s = pd.Series([2, None, 3], dtype="Int64") print(len(s), int(s.count()))

  • 2 2
  • 3 3
  • 2 3
  • 3 2

Answer: 3 2. Length includes the missing row; count includes known values.

What does this program print? import pandas as pd s = pd.Series([2, None, 3], dtype="Int64") print(s.isna().tolist())

  • [False, True, False]
  • [False, False, False]
  • [True, False, True]
  • [2, None, 3]

Answer: [False, True, False]. The missingness mask marks the unknown observation.

Which environment must receive a local Pandas installation?

  • Any Python installation on the machine
  • The interpreter or notebook kernel that will run the code
  • Only the browser developer console
  • Only the operating system shell profile

Answer: The interpreter or notebook kernel that will run the code. Installing into a different interpreter does not supply the package to the selected runtime.

What does this program print? import pandas as pd frame = pd.DataFrame({"name": ["A", "B"], "qty": [1, 2]}) print(frame.columns.tolist())

  • ['A', 'B']
  • [0, 1]
  • ['name', 'qty']
  • ['name', 'A', 'B']

Answer: ['name', 'qty']. Dictionary keys identify the columns in this construction.

A total skips one missing observation. What can you conclude?

  • The missing observation was zero
  • The full dataset was validated
  • The file fits in memory
  • The total covers the known observations under that operation’s policy

Answer: The total covers the known observations under that operation’s policy. A computed number cannot establish the meaning of missing data.

Continue this course

Related lessons