Understand the idea
read_csv reads a text file into a DataFrame. The separator tells pandas where one field ends and the next begins.
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")
dfWhat 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 | 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 |
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
- Load the supplied candy.csv into df and display the imported table.
- 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