Start learning free

LESSON 9 OF 165 · MACHINE LEARNING: PANDAS

Open a Table: read_csv

Practice

Data often comes as a CSV file: a table saved as plain text, one line per row, with the values split by commas. Its first line, the header, names the columns. The shop keeps its customers in customers.csv: 300 customers, 11 columns.

pandas is the Python library for tables; you load it with import pandas as pd. pd.read_csv("file.csv") reads a CSV file and gives back a DataFrame: a table with named columns and a label on every row, counted 0, 1, 2, … from the top. On a small file of pets:

import pandas as pd

pets = pd.read_csv("pets.csv")
print(pets.head(2).to_string())
print(len(pets))

pets.head(2) gives back a small table with the first 2 rows; with no number, head() gives 5. tail(n) gives back the last n rows. .to_string() turns a table into text with every column shown. .shape is a pair, (rows, columns), len(...) gives back the number of rows as on a list, and type(...) names the kind of value. A blank cell in the file shows as NaN: a missing value.

Your script must print this (long lines are cut here with …):

<class 'pandas.DataFrame'>
   customer_id    city   age      joined newsletter …
0            1    Rome  52.0  2026-09-25        yes …
1            2  Madrid  41.0  2026-08-10        yes …
2            3  Madrid  51.0  2026-06-16         no …
3            4    Lyon  24.0  2026-05-18         no …
4            5    Rome  61.0  2026-02-21         no …
     customer_id  city   age      joined newsletter …
298          299  Cluj  39.0  2026-01-15        yes …
299          300   NaN   NaN  2026-06-10        yes …
Shape: (300, 11)
Rows: 300

Your task: below the import, read customers.csv into df. Then print the type of df, its first 5 rows and its last 2 rows (each with .to_string()), "Shape:" with its shape, and "Rows:" with its number of rows.


Assignment
Follow the Coding Tutorial to open customers.csv as a DataFrame, peek at its first and last rows, and measure its size.


Hint
A DataFrame's methods go after a dot: df.head(), df.tail(2). df.shape has no parentheses: it is a value, not a method. len(df) works as on a list.


STEP 1 OF 6
    Ctrl + Enter to check