Introduction to Pandas in Python: First Steps
Pandas is an open-source Python library used to organise, clean, transform and analyse structured data. It is especially useful when information is arranged in rows and columns, such as sales records, student marks, customer information, survey responses or financial data. In this introduction to Pandas, you will learn what the library does, how to install it, how to import it, and how to run your first examples.
You do not need to learn every Pandas function at once. Start by understanding the two core data structures—Series and DataFrame—and practise loading and inspecting a small dataset. Later lessons in this tutorial cover these structures and individual operations in more depth.
- What is Pandas?
- Why use Pandas?
- What should you know first?
- How to install Pandas
- Import Pandas in Python
- Your first Pandas example
- Series and DataFrame explained
- Load a dataset from a CSV file
- Inspect and understand a dataset
- A typical Pandas workflow
- Common beginner mistakes
- What to learn next
- Frequently asked questions
What Is Pandas in Python?
Pandas is a library that adds convenient data structures and tools for working with labelled data. Instead of manually processing every item in a table, you can use Pandas to select columns, filter rows, calculate summaries, handle missing values and combine datasets.
Imagine a small table recording product sales. Each row represents a sale, and each column represents a variable, such as the product name, quantity and price. A Pandas DataFrame can represent this table directly in Python.
import pandas as pd
sales = {
"Product": ["Notebook", "Pen", "Bag"],
"Quantity": [4, 10, 2],
"Price": [250, 30, 1200]
}
df = pd.DataFrame(sales)
print(df)
Output
Product Quantity Price 0 Notebook 4 250 1 Pen 10 30 2 Bag 2 1200
The variable df contains the table. The dictionary keys become the column labels, and the lists provide the values for each column. The numbers on the left are the DataFrame's row index.
Why Use Pandas?
Pandas is useful because real datasets often need to be explored and prepared before you can answer questions or build a model. Common tasks include:
- Read data: load CSV files and Excel spreadsheets into Python.
- Explore data: check the number of rows and columns, column names, data types and summary statistics.
- Select relevant information: work with specific columns or records that meet a condition.
- Clean datasets: identify missing values, remove duplicate records and correct inconsistent values.
- Summarise information: calculate totals, averages, counts and grouped statistics.
- Combine tables: join data from different sources using common identifiers.
- Prepare data for analysis: arrange and check features before using visualisation or machine-learning tools.
For example, a business analyst might use Pandas to find monthly sales by region. A student might use it to explore a survey dataset. A machine-learning practitioner might use it to inspect missing values and select input columns before training a model.
What Should You Know Before Learning Pandas?
You can begin learning Pandas without being an advanced Python programmer, but a few basics will make the examples easier to understand.
| Python concept | Why it helps | Example |
|---|---|---|
| Variables | Store a DataFrame or a result for later use. | df = ... |
| Lists | Understand collections of values used to create columns. | [10, 20, 30] |
| Dictionaries | Understand column names mapped to lists of data. | {"Age": [20, 21]} |
| Functions and methods | Call operations on Pandas objects. | df.head() |
| Indexing | Understand how rows and columns are selected. | df["Age"] |
If lists, dictionaries or function calls are unfamiliar, review the relevant Python tutorial first. You can also learn these concepts alongside the Pandas examples.
How to Install Pandas
Pandas is not part of Python's standard library, so it normally needs to be installed in the Python environment you plan to use. Choose the instructions that match your setup.
Install Pandas with pip
Open Command Prompt or a terminal and run:
python -m pip install pandas
Using python -m pip helps run pip through the selected Python interpreter. On some systems, the command may be python3 -m pip install pandas. If you use a virtual environment, activate it before installing packages.
Install Pandas in Anaconda
If you use Anaconda, Pandas is commonly available in many standard data-science environments. If it is missing, open Anaconda Prompt for the environment you use and run:
conda install pandas
Install Pandas in Jupyter Notebook
Install Pandas in the same environment that runs the notebook kernel. If your notebook supports the pip magic command, you can run:
%pip install pandas
import pandas fails in another, the terminal and notebook may be using different interpreters. Check which environment is active before reinstalling packages.Check Whether Pandas Is Installed
After installation, run a short import test and display the installed version:
import pandas as pd
print(pd.__version__)
If the code prints a version string without an import error, Pandas is available to that Python environment. The version number depends on the version installed on your computer.
How to Import Pandas in Python
Import the library at the beginning of a script or notebook:
import pandas as pd
The letters pd are a widely used alias for Pandas. It is not mandatory, but following this convention makes examples easier to read and compare with other tutorials. You then access Pandas functions and classes through pd, for example pd.DataFrame() and pd.Series().
Importing the library does not automatically load any dataset. You create data in Python or read it from a file in a separate step.
Your First Pandas Example
Let's create a simple table of student marks and calculate the average. This example introduces the DataFrame, selecting a column and using a summary operation.
import pandas as pd
students = {
"Name": ["Amina", "Hamza", "Sara", "Omar"],
"Marks": [78, 91, 84, 69]
}
df = pd.DataFrame(students)
print(df)
print("Average marks:", df["Marks"].mean())
Output
Name Marks 0 Amina 78 1 Hamza 91 2 Sara 84 3 Omar 69 Average marks: 80.5
In this example:
pd.DataFrame(students)creates a table from a dictionary.df["Marks"]selects the Marks column as a Series..mean()calculates the arithmetic mean of the numeric values.
This is one reason Pandas is convenient for data analysis: many common calculations can be applied directly to a column without writing a loop yourself.
Pandas Series and DataFrame Explained
The two core Pandas data structures are the Series and DataFrame. Understanding the difference helps you follow almost every later lesson.
What Is a Pandas Series?
A Series is a one-dimensional labelled array. You can think of it as a single column of data with an index attached.
import pandas as pd
marks = pd.Series([78, 91, 84], name="Marks")
print(marks)
What Is a Pandas DataFrame?
A DataFrame is a two-dimensional labelled data structure organised into rows and columns. Different columns may contain different data types. For tabular data such as a CSV file, a DataFrame is usually the main object you work with.
| Feature | Series | DataFrame |
|---|---|---|
| Dimensions | One-dimensional | Two-dimensional |
| Typical representation | One variable or column | A table with multiple columns |
| Example | Marks for several students | Student names, marks and grades |
| Common creation method | pd.Series() | pd.DataFrame() |
Continue to the dedicated Pandas Series tutorial and Pandas DataFrame tutorial for more detailed explanations.
How to Load Data from a CSV File
In practice, data often comes from a file rather than being typed into Python. The read_csv() function loads a comma-separated values (CSV) file into a DataFrame.
import pandas as pd
df = pd.read_csv("sales.csv")
print(df.head())
In this example, sales.csv must be accessible from the program's working directory, or you must provide the correct file path. A CSV file usually stores column names in its first row, which Pandas uses as column labels by default.
FileNotFoundError usually means Python cannot find the file at the supplied path. Check the current working directory and the spelling of the filename. In a notebook, you can inspect the working directory with Python's os.getcwd().For more options, including reading selected columns and handling different delimiters, see the Pandas read_csv tutorial.
How to Inspect a Dataset with Pandas
After loading data, inspect it before performing calculations. These methods answer different questions about a DataFrame.
| Method or property | What it tells you |
|---|---|
df.head() | Shows the first five rows by default. |
df.tail() | Shows the last five rows by default. |
df.shape | Returns a tuple containing the number of rows and columns. |
df.columns | Lists the column labels. |
df.info() | Summarises columns, non-null counts and data types. |
df.describe() | Summarises numeric columns by default. |
print(df.head())
print("Shape:", df.shape)
print("Columns:", df.columns)
df.info()
print(df.describe())
These checks can reveal problems early. For example, unexpected column names may indicate that the file was parsed incorrectly; a smaller non-null count can indicate missing values; and an incorrect data type can affect calculations.
A Typical Pandas Workflow
A practical data-analysis task often follows this sequence:
- Import: import Pandas using
import pandas as pd. - Load: read the dataset from a CSV file, spreadsheet or another source.
- Inspect: check the first rows, dimensions, column names and data types.
- Clean: investigate missing values, duplicates and inconsistent entries.
- Transform: select columns, filter records, create calculated columns or combine tables.
- Analyse: calculate descriptive statistics and group-level summaries.
- Communicate or model: export results, visualise patterns or prepare data for a machine-learning workflow.
This process is iterative. You may discover a data-quality issue during analysis and return to the cleaning step. For machine learning, fit preprocessing steps only on training data when they learn parameters from the data, then apply those fitted transformations to validation or test data to avoid information leakage.
Common Beginner Mistakes
1. Forgetting to import Pandas
If you call pd.DataFrame() before importing Pandas as pd, Python will raise a NameError. Start the script with import pandas as pd.
2. Installing Pandas in the wrong environment
If installation succeeds but importing fails, check that your editor or notebook uses the same Python environment where Pandas was installed.
3. Using a filename that Python cannot locate
Use the correct file path and check the working directory. The file does not need to be in the same folder if you supply a valid path.
4. Confusing a Series with a DataFrame
Selecting one column with df["Marks"] normally returns a Series. Selecting it with double brackets, df[["Marks"]], returns a DataFrame containing one column.
marks_series = df["Marks"]
marks_dataframe = df[["Marks"]]
print(type(marks_series))
print(type(marks_dataframe))
5. Assuming every column is numeric
Numbers can be imported as text if a file contains inconsistent formatting or special characters. Inspect data types with df.info() before calculating statistics.
What to Learn After This Pandas Introduction
Once you understand what Pandas is and can run a basic example, follow these lessons in order:
- Pandas DataFrame tutorial — learn how to inspect and work with tabular data.
- Pandas Series tutorial — understand one-dimensional labelled data.
- How to create a DataFrame — build DataFrames from lists, dictionaries and arrays.
- Read CSV files with Pandas — import a real dataset.
- Select rows and columns — retrieve the information you need.
- Filter a DataFrame — select records that meet conditions.
Return to the complete Python Pandas tutorial for the full lesson roadmap.
Frequently Asked Questions About Pandas
What is Pandas used for in Python?
Pandas is used to load, organise, clean, transform and analyse structured data. It is commonly used in data analysis, data science, reporting and data preparation for machine learning.
Is Pandas included with Python?
No. Pandas is a separate library and is usually installed with pip or conda. Some data-science environments already include it.
How do I install Pandas?
For a typical Python installation, run python -m pip install pandas in a terminal. If you use Anaconda, you can use conda install pandas in the relevant environment.
What does import pandas as pd mean?
It imports the Pandas library and assigns it the short alias pd. You can then call functions such as pd.DataFrame() and pd.read_csv().
Should I learn Python before Pandas?
Basic knowledge of Python variables, lists, dictionaries, functions and indexing is helpful. You do not need to master all of Python before starting Pandas.
What is the difference between a Pandas Series and DataFrame?
A Series is one-dimensional and is often used for one column of labelled values. A DataFrame is two-dimensional and organises data into rows and columns.
Can I use Pandas for machine learning?
Yes. Pandas is often used to load, inspect, clean and prepare datasets. Machine-learning models are commonly trained and evaluated with libraries such as scikit-learn or specialised deep-learning frameworks.
