2. Reading and inspecting data
2.1 Reading a CSV file
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
Most data arrives as CSV (comma-separated values): plain text where each line is a row and commas separate the columns. pd.read_csv("orders.csv") turns such a file into a DataFrame in one line.
- The first line becomes the column names
- Numbers become numeric columns automatically
- Text stays as text
The browser can’t see files on your laptop, so these examples wrap CSV text in io.StringIO(...), which makes text behave like a file. On your laptop, pass the file path instead.
Same call, two sources
- On your laptop:
pd.read_csv("orders.csv") - In these lessons:
pd.read_csv(io.StringIO(text)) - Both give you the same DataFrame
If the file is in another folder, give its path, such as pd.read_csv("data/orders.csv"). A wrong path raises FileNotFoundError.
How it fits together
- orders.csv (text)
- pd.read_csv(...)
- DataFrame
Step through the code
Python
import ioimport pandas as pdtext = "city,amount\nNoida,250\nDelhi,400\nPune,150"orders = pd.read_csv(io.StringIO(text))print(orders)print(orders["amount"].sum())
Output
city amount 0 Noida 250 1 Delhi 400 2 Pune 150 800
Practice in pandas ✓ Solved
Read the CSV text into df and print the number of rows.
Expected output
3
Reference solution
import io
import pandas as pd
text = "name,score\nAsha,88\nRavi,92\nMeera,79"
df = pd.read_csv(io.StringIO(text))
print(len(df))
Question 1 · Easy
Which function reads a CSV file into a DataFrame?
Question 2 · Medium
A CSV file has a header line and 5 data lines. How many rows does the DataFrame have?
Question 3 · Hard
pd.read_csv("orders.csv") raises FileNotFoundError. What is the most likely cause?
Key takeaways
pd.read_csv turns a CSV file into a DataFrame: the first line becomes the column names and numbers become numeric columns.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in