Pandas Tutorial menu

Pandas Introduction

Pandas is a Python library that makes it easy to load, clean, explore and analyse data.

What is Pandas?

  • Pandas is a free, open-source Python library for data analysis
  • It was created by Wes McKinney in 2008
  • The name comes from "panel data", a term used in statistics
  • It is built on top of NumPy, so it is fast

What Can Pandas Do?

TaskExample
Load dataRead a CSV file of 50,000 orders
ExploreSee the first rows, column types and averages
CleanFill empty cells, remove duplicates, fix types
FilterKeep only orders from Karachi above Rs 5000
SummariseTotal sales per city, per month
SaveWrite the result to a new CSV or Excel file

Installing Pandas

Install it from the terminal with pip:

Example

bash
pip install pandas

In Anaconda and Google Colab, Pandas is already installed. Google Colab is a good free choice if you do not want to install anything.

Importing Pandas

Pandas is always imported with the short name pd:

Example

python
import pandas as pd
print(pd.__version__)
Output
3.0.5

Your version may be different. The outputs in this tutorial come from Pandas 3. Version 2 works too, with a few small differences that we point out.

The Two Main Objects

ObjectWhat it isLike in Excel
SeriesOne column of data with labelsA single column
DataFrameA table of rows and columnsA whole sheet

A Series:

Example

python
import pandas as pd

temps = pd.Series([31, 33, 29], index=["Karachi", "Lahore", "Quetta"])
print(temps)
Output
Karachi    31
Lahore     33
Quetta     29
dtype: int64

A DataFrame:

Example

python
import pandas as pd

students = pd.DataFrame({
    "name": ["Ali", "Ayesha", "Hamza"],
    "age": [19, 20, 18],
    "city": ["Karachi", "Hyderabad", "Karachi"]
})
print(students)
Output
     name  age       city
0     Ali   19    Karachi
1  Ayesha   20  Hyderabad
2   Hamza   18    Karachi

The numbers 0, 1, 2 on the left are the index, the label of each row. Pandas adds them automatically.

Where to Write Pandas Code

Pandas works in any Python file, but many people use Jupyter Notebook or Google Colab. In a notebook, the last line of a cell is shown automatically, and tables appear nicely formatted. In a normal .py file, use print() as in this tutorial.

Exercise

Exercise

What short name is normally used when importing Pandas?

Learn Pandas with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp