Menu
CoddyTech

Reading CSV Files

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 33 of 60.

Real datasets have thousands of rows, so they live in files. The most common is the CSV file: plain text, one row per line, values split by commas.

The text file books.csv on the left, a header line title, pages, year and three lines of books, with an arrow to the DataFrame it becomes on the right: the header turns into column names, each line into a row

pd.read_csv takes the file's name and returns a DataFrame:

books = pd.read_csv("books.csv")
print(books)

This prints:

     title  pages  year
0     Dune    412  1965
1     Emma    474  1815
2  Beloved    324  1987

The first line named the columns, and numbers came in as numbers, ready for math. On Coddy, a lesson's files sit next to your program, so the name is enough.

challenge icon

Challenge

Medium

A coffee shop saves one CSV file per day, monday.csv, tuesday.csv and so on, each with the columns drink and cups. The program reads a day in lowercase into day.

Build that day's file name, load the file into a DataFrame orders and print it.

If the day were sunday and sunday.csv held drink,cups, mocha,5 and chai,13, you would see:

   drink  cups
0  mocha     5
1   chai    13

Try it yourself

import pandas as pd

day = input()

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler