Python tutoring online
Home

Pandas DataFrame Tutorial: Create, Access and Explore Data

A Pandas DataFrame is a two-dimensional, labelled data structure with rows and columns. It is one of the main objects used in Python data analysis because it can represent tables such as sales records, student results, customer details, survey responses and financial data. In this Pandas DataFrame tutorial, you will learn how a DataFrame is organised, how its index and columns work, and how to inspect its size, data types and summary statistics using practical examples.

This page focuses on understanding and exploring an existing DataFrame. For a deeper guide to building tables from dictionaries, lists and arrays, continue to how to create a Pandas DataFrame. If you are new to the library, first read the introduction to Pandas.

Learn Pandas with Practical Guidance

If you need help with Python, Pandas, data analysis coursework or a project, one-to-one tutoring can help you understand the code and practise with real datasets.

Get 1-on-1 Python Tutoring

What Is a Pandas DataFrame?

A DataFrame is a table-like object provided by the pandas library. It has two axes: an index for rows and column labels for fields. Each column can contain a different data type, so a single DataFrame can hold text, integers, decimal values, dates and Boolean values in separate columns.

For example, a student dataset might have one row per student and columns for name, age, course and marks. A sales dataset might have columns for product, quantity, unit price and revenue. A DataFrame lets you inspect, select, calculate and transform this data using Python.

A First Pandas DataFrame Example

Import Pandas using the common alias pd, then create a small table of product sales. This example is self-contained, so you can run it in a Python script or Jupyter Notebook after installing Pandas.

Python
import pandas as pd

sales = {
    "Product": ["Laptop", "Phone", "Tablet", "Monitor"],
    "Category": ["Computers", "Mobiles", "Computers", "Accessories"],
    "Units": [3, 5, 4, 2],
    "Unit_Price": [800, 500, 300, 220]
}

df = pd.DataFrame(sales)
df["Revenue"] = df["Units"] * df["Unit_Price"]

print(df)

Output

    Product     Category  Units  Unit_Price  Revenue
0    Laptop    Computers      3         800     2400
1     Phone       Mobiles      5         500     2500
2    Tablet    Computers      4         300     1200
3   Monitor  Accessories      2         220      440

The variable df now stores a DataFrame. The dictionary keys became the column names, and each list supplied the values for one column. The new Revenue column is calculated by multiplying the matching values in Units and Unit_Price.

Notice the numbers at the left of the output: 0, 1, 2 and 3. These are the row index labels. They are not automatically treated as a normal data column.

Pandas DataFrame Structure: Rows, Columns and Index

Understanding the parts of a DataFrame makes it easier to read code and diagnose errors.

PartMeaningExample in the sales table
RowA single record or observation.The row containing Laptop sales.
ColumnA named variable or field.Product, Units or Revenue.
IndexLabels used to identify rows.0, 1, 2, 3.
ValuesThe data stored in the table."Laptop", 3 and 2400.

By default, Pandas usually assigns a RangeIndex starting at zero when you create a DataFrame from lists or dictionaries without specifying an index. The index can also contain meaningful labels, such as student IDs or dates. Index labels do not have to be unique, although unique labels are often easier to work with.

Python
import pandas as pd

marks = pd.DataFrame(
    {"Name": ["Amina", "Bilal", "Sara"], "Marks": [86, 73, 92]},
    index=["S101", "S102", "S103"]
)

print(marks)
print("Index labels:", marks.index.tolist())

Output

       Name  Marks
S101  Amina     86
S102  Bilal     73
S103   Sara     92
Index labels: ['S101', 'S102', 'S103']

Here, the student codes are index labels. They help identify rows, but they are not a column named StudentID. If you want the index to become a regular column, you can use reset_index().

Python
marks_as_columns = marks.reset_index(names="StudentID")
print(marks_as_columns)
Remember: a row's displayed index label is different from its position. A label might be S103 or a date, while its position is the row's location within the current DataFrame.

DataFrame shape, size and dimensions

Pandas provides several attributes for quickly checking the size of a DataFrame. These are attributes, not methods, so do not add parentheses to them.

AttributeWhat it returnsExample
df.shapeA tuple containing (number of rows, number of columns).(4, 5)
df.sizeTotal number of data cells: rows multiplied by columns.20
df.ndimNumber of dimensions. A DataFrame has two.2
len(df)Number of rows.4
Python
print("Shape:", df.shape)
print("Rows:", df.shape[0])
print("Columns:", df.shape[1])
print("Number of cells:", df.size)
print("Dimensions:", df.ndim)
print("Rows using len():", len(df))

For a DataFrame with four rows and five columns, df.shape is (4, 5). The first number always represents rows and the second represents columns. This is useful when checking whether a file loaded as expected or whether an operation changed the table's dimensions.

Inspect DataFrame Column Names and Index

The columns and index attributes let you inspect the labels used in a DataFrame. These are especially useful when working with unfamiliar datasets or when column names contain spaces, inconsistent capitalisation or unexpected characters.

Python
print(df.columns)
print(df.index)

# Convert column labels to a regular Python list
print(df.columns.tolist())

To check whether a particular column exists, you can test its name against df.columns:

Python
if "Revenue" in df.columns:
    print("Revenue column is available")
else:
    print("Revenue column is missing")

This check can prevent a KeyError when your code expects a column that is not present. Remember that column names are case-sensitive: Revenue, revenue and REVENUE are different labels.

Preview Data with head(), tail() and sample()

Before analysing a dataset, it is good practice to view a few rows. Pandas provides three convenient methods for previewing records.

Python
print(df.head())       # First five rows (or fewer if there are fewer rows)
print(df.head(2))    # First two rows
print(df.tail(3))    # Last three rows
print(df.sample(2, random_state=42))  # Two reproducible random rows

The optional number controls how many rows are returned. Setting random_state makes the random sample reproducible, which is helpful when teaching, testing or comparing results. The sample still depends on the data and the requested sample size.

Tip: use head() to check that a file loaded correctly, but do not assume the first few rows represent the whole dataset. Use summaries and appropriate plots to understand the broader data.

Understand DataFrame info() and Data Types

The info() method prints a compact technical summary of a DataFrame. It typically shows the index range, column names, non-null counts, data types and memory usage. This is one of the most useful first checks after reading a dataset.

Python
df.info()

For the sales example, the output will describe five columns and four data rows. Exact formatting and memory figures can vary with your Pandas version and environment.

The dtypes attribute gives the data type for each column:

Python
print(df.dtypes)

Common data types include:

TypeTypical valuesWhy it matters
int643, 12, 250Whole-number calculations and counts.
float6412.5, 99.95Decimal or numeric measurements.
object / string-like"Laptop", "North"Often text, though object columns can contain other Python objects.
boolTrue, FalseLogical flags and conditions.
Datetime types2026-01-05Date and time calculations, filtering and ordering.

A column that contains numbers may be loaded as text if the source file contains symbols, spaces or inconsistent values. Check the actual contents before converting types. For more advanced cleaning, see the lessons on handling missing values and renaming columns and replacing values.

Calculate Summary Statistics with describe()

The describe() method generates descriptive statistics for selected columns. For numeric data, the default summary typically includes the count, mean, standard deviation, minimum, quartiles and maximum. It is a quick way to identify ranges and possible unusual values.

Python
print(df.describe())

Because the sales table includes numeric columns, describe() summarises them by default. You can also ask for a summary of all columns:

Python
print(df.describe(include="all"))

For text columns, the summary may include the number of non-missing values (count), unique values (unique), the most frequent value (top) and its frequency (freq). Some statistics are not meaningful for every data type, so Pandas may leave those entries empty.

Summary statistics are useful for initial exploration, but they do not explain the context of the data by themselves. For example, a high maximum value might be a genuine large transaction or a data-entry error. Investigate unexpected values before changing or deleting them.

Select a DataFrame Column

Although this page concentrates on DataFrame structure and inspection, selecting a column is an essential first operation. Use the column label inside square brackets to return a Series:

Python
products = df["Product"]
print(products)
print(type(products))

To select more than one column, pass a list of column labels. The result remains a DataFrame:

Python
product_summary = df[["Product", "Units", "Revenue"]]
print(product_summary)
print(type(product_summary))

Note the difference between df["Product"] and df[["Product"]]: the first returns a Series, while the second returns a one-column DataFrame. This distinction matters when later code expects a table or a single labelled sequence.

For detailed row and column selection—including loc and iloc—read the dedicated Pandas row and column selection tutorial.

Pandas DataFrame vs Series

A Series is one-dimensional and usually represents one column of values. A DataFrame is two-dimensional and combines one or more columns under a shared row index. Selecting a single column from a DataFrame commonly returns a Series.

FeatureSeriesDataFrame
DimensionsOne-dimensionalTwo-dimensional
StructureOne labelled sequenceRows and columns
ExampleOne column of marksStudent names, marks and grades
Typical creationpd.Series(...)pd.DataFrame(...)
Dimension attributeseries.ndim is 1df.ndim is 2

Continue to the Pandas Series tutorial to learn about one-dimensional labelled data, or the DataFrame creation guide to explore different ways to build a table.

Practical DataFrame Inspection Workflow

When you receive a new dataset, use a consistent sequence of checks before you start detailed analysis. The following code combines the main inspection methods from this tutorial.

Python
import pandas as pd

# Example: df is an existing DataFrame
print("First rows:")
print(df.head())

print("Shape (rows, columns):", df.shape)
print("Column names:", df.columns.tolist())

print("Data types and non-null counts:")
df.info()

print("Summary statistics:")
print(df.describe(include="all"))

print("Missing values per column:")
print(df.isna().sum())

This workflow helps answer several basic questions:

  1. Did the data load, and do the first rows look sensible?
  2. How many rows and columns are present?
  3. Are the expected column names available?
  4. Were columns interpreted as the correct data types?
  5. Are there missing values or suspicious summary statistics to investigate?

Once you understand the structure, you can move on to filtering records, sorting rows, grouping data and cleaning values. For example, the Pandas filtering tutorial explains how to select records that meet conditions, while the Pandas groupby tutorial covers grouped summaries.

Common Pandas DataFrame Mistakes

1. Treating shape as a method

df.shape is an attribute, so use it without parentheses. By contrast, df.head(), df.tail(), df.info() and df.describe() are methods and use parentheses.

2. Confusing row position with index labels

The first displayed row often has index label 0, but after filtering or reordering the index may retain its original labels. Do not assume that a row label always equals its current position.

3. Assuming a column exists or has the expected spelling

Column labels are case-sensitive and may include spaces. Inspect df.columns when a column selection raises a KeyError.

4. Assuming every numeric-looking value is numeric

Values such as "1,200", "£45" or mixed text and numbers may be read as strings. Inspect df.dtypes and check the source values before converting them.

5. Relying only on the first few rows

head() is a preview, not a full quality check. Combine it with info(), describe(), missing-value checks and domain knowledge.

Frequently Asked Questions About Pandas DataFrames

What is a DataFrame in Pandas?

A Pandas DataFrame is a two-dimensional, labelled data structure with rows and columns. It is commonly used to store and analyse tabular data in Python.

How do I create a Pandas DataFrame?

Use pd.DataFrame(). You can pass a dictionary of lists, a list of dictionaries, arrays or other supported data structures. See the full guide to creating a Pandas DataFrame for examples.

How do I see the number of rows and columns in a DataFrame?

Use df.shape. It returns a tuple in the form (rows, columns). For just the number of rows, use len(df) or df.shape[0]; for the number of columns, use df.shape[1].

What is the difference between head() and tail()?

head() displays the first rows, while tail() displays the last rows. Both return five rows by default and accept a number to specify a different amount.

What does info() do in Pandas?

df.info() prints a compact summary of the DataFrame, including column names, non-null counts, data types and memory information.

What does describe() do in Pandas?

df.describe() calculates descriptive statistics for numeric columns by default. Use df.describe(include="all") to request summaries for other column types as well.

Is a Pandas DataFrame the same as a table in Excel?

They are similar in that both can represent data in rows and columns. An Excel worksheet is part of a spreadsheet application, while a DataFrame is a Python object that can be manipulated programmatically and integrated into repeatable data-analysis workflows.

What should I learn after DataFrames?

Learn how to select rows and columns, filter records, sort values, read CSV and Excel files, handle missing values and group data for summaries. The complete Pandas tutorial roadmap links to these topics.

Continue Learning Pandas

You now know the main parts of a Pandas DataFrame and how to inspect its structure before analysis. Use these lessons to build on what you have learned:

Need Help with Pandas or Data Analysis?

Get support with DataFrames, data cleaning, exploratory data analysis, Python programming or a data-analysis assignment through one-to-one online tutoring.

Explore Python Tutoring



Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net