BBampaa

Lessons › Python

Python lesson

Loading a CSV

pandas loads the file into a DataFrame: a table you can work with in code. The last line of a cell is shown automatically, so df.head() displays without print.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

pandas is Python's table toolkit. Three lines load the shop's orders and show the top of the table:

import pandas as pd
df = pd.read_csv("orders.csv")
df.head()

Output:

Order Day Store Product Qty Revenue
0 O101 Mon Lagos Earbuds 2 70
1 O102 Mon Abuja Charger 1 15
2 O103 Tue Lagos Phone case 3 24
3 O104 Wed Lagos Earbuds 1 35
4 O105 Wed Abuja Earbuds 4 140

Key points

import pandas as pdLoad pandas. pd is the short name everyone uses.
pd.read_csv("orders.csv")Read a file into a table, called a DataFrame.
df.head()Show the first 5 rows. df.head(3) shows 3.

Most analysis in Python starts like this: import, read, and look.

Practice

Try each one in your head first, then open the answer.

1. Build the line that loads orders.csv into a variable called df.
df = pd.read_csv("orders.csv")
2. Build a line that shows the first 3 rows.
df.head(3)
3. Import pandas, load orders.csv into df, and show the first 5 rows.
import pandas as pd
df = pd.read_csv("orders.csv")
df.head()
4. Show the first 2 rows of df.
df.head(2)
5. Load orders.csv into df (pandas is already imported as pd), then show the first 4 rows.
df = pd.read_csv("orders.csv")
df.head(4)

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed