Read CSV Data with pandas
pandas can load comma-separated data from a file or any file-like object such as StringIO.
When is pandas read_csv used?
CSV commonly moves data between spreadsheets, business systems, analytics tools, APIs, and databases. pandas.read_csv() converts it into a DataFrame for cleaning, filtering, analysis, and visualization.
Common use cases
- Analyze exports from Excel, Google Sheets, or a CRM.
- Load datasets for machine learning and data science.
- Clean missing, incorrectly typed, or duplicated data before import.
Basic example
import pandas as pd
from io import StringIO
csv_text = "name,score\nAda,95\nLin,88\nSam,91"
students = pd.read_csv(StringIO(csv_text))
print(students)
Expected output
name score
0 Ada 95
1 Lin 88
2 Sam 91
Advanced example
Real CSV files are often large and imperfect. This example selects required columns, parses dates, controls data types, and recognizes several missing-value formats.
import pandas as pd
sales = pd.read_csv(
"sales.csv",
usecols=["order_date", "product", "quantity", "revenue"],
parse_dates=["order_date"],
dtype={"product": "string", "quantity": "Int64"},
na_values=["", "N/A", "unknown"],
)
sales = sales.dropna(subset=["order_date", "product"])
monthly_revenue = sales.groupby(
sales["order_date"].dt.to_period("M")
)["revenue"].sum()
print(monthly_revenue)
How it works
StringIO makes the text behave like an open file, allowing read_csv to parse it without creating a temporary file.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Add rows, columns, and missing values.
- Combine filtering, sorting, and groupby into a small report.
- Load a real file, inspect dtypes, and handle invalid data.