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?
| Task | Example |
|---|---|
| Load data | Read a CSV file of 50,000 orders |
| Explore | See the first rows, column types and averages |
| Clean | Fill empty cells, remove duplicates, fix types |
| Filter | Keep only orders from Karachi above Rs 5000 |
| Summarise | Total sales per city, per month |
| Save | Write the result to a new CSV or Excel file |
Installing Pandas
Install it from the terminal with pip:
Example
pip install pandasIn 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
import pandas as pd
print(pd.__version__)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
| Object | What it is | Like in Excel |
|---|---|---|
Series | One column of data with labels | A single column |
DataFrame | A table of rows and columns | A whole sheet |
A Series:
Example
import pandas as pd
temps = pd.Series([31, 33, 29], index=["Karachi", "Lahore", "Quetta"])
print(temps)Karachi 31 Lahore 33 Quetta 29 dtype: int64
A DataFrame:
Example
import pandas as pd
students = pd.DataFrame({
"name": ["Ali", "Ayesha", "Hamza"],
"age": [19, 20, 18],
"city": ["Karachi", "Hyderabad", "Karachi"]
})
print(students)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?
