Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Data Foundations · A little practice goes a long way.

← Inspect lessonsTINY TABLES · REAL PYTHON · YOUR PACE
Getting oriented · I01CSV · 8 MIN

Load a CSV

Load a file and inspect what arrived.

Exercises within this concept

  1. FollowFollow the techniqueCurrent exercise
  2. ChangeAdapt the workflow
  3. TransferCombine earlier skills

Understand the idea

read_csv reads a text file into a DataFrame. The separator tells pandas where one field ends and the next begins.

Concept sketch: CSV text → DataFrametiny.csvname,priceA,2B,4namepriceA2B4CSV text → DataFrame
Illustration · not the exercise output

A small example

name;age followed by Ada;4 needs sep=";" to become two columns, name and age.

Follow the code

Apply the idea to the supplied table. Read from top to bottom; the final line displays the result.

import pandas as pd

df = pd.read_csv("candy.csv")
df

What each part does

pd
the short name given to pandas
read_csv(...)
read a comma-separated file as a DataFrame
"candy.csv"
the file path, written as text
df =
store the returned DataFrame in df
Other choices for later exercises
sep=";"
Use semicolons rather than the default commas to separate fields.

Available file

Available file: candy.csv. Load the file in your code; no table is loaded for you.

Candy shop · 6 synthetic rows
candyflavourpriceratingshelf
Gummy Bearfruity1.24.1A
Choco Popchocolate2.14.6B
Mint Bitemint1.53.8A
Berry Loopfruity2.84.4B
Cocoa Cubechocolate3.44.9A
Lemon Dropfruity1.84B

File · candy.csv

This file is available in the lesson folder. Load it to create df.

candy,flavour,price,rating,shelf
"Gummy Bear","fruity",1.2,4.1,"A"
"Choco Pop","chocolate",2.1,4.6,"B"
"Mint Bite","mint",1.5,3.8,"A"
"Berry Loop","fruity",2.8,4.4,"B"
"Cocoa Cube","chocolate",3.4,4.9,"A"
"Lemon Drop","fruity",1.8,4,"B"

Your task · Follow

  1. Load the supplied candy.csv into df and display the imported table.
  2. Use: read_csv().
Hint

read_csv returns a DataFrame; assign it before displaying it.

Reveal solution

One way to do it. Keep any supplied setup in the editor and use this in the Your work section.

import pandas as pd

df = pd.read_csv("candy.csv")
df
Your task · Follow
  1. Load the supplied candy.csv into df and display the imported table.
  2. Use: read_csv().

Tab: indent · Shift+Tab: outdent · Esc, then Tab: leave editor

Edit Python. Control or Command plus Enter runs it. Tab indents by four spaces. Shift plus Tab outdents. Press Escape, then Tab or Shift plus Tab to leave the editor.

Each run executes all editor code in a fresh Python session. Display a value by leaving it on the final line.

Python starts when you open a lesson.

Output

Run your code to see what Python returns.