Reading CSV Files
Load CSV files with pd.read_csv, control delimiters, header rows, and index columns, and preview the result.
Reading CSV Files is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why CSV Is the Universal Format
CSV (Comma-Separated Values) is the most widely used format for exchanging tabular data. It is human-readable, supported by every database, spreadsheet, and analytics tool, and requires no schema definition. pd.read_csv() is the most frequently called Pandas function in data analysis because virtually every public dataset, API export, or database dump is available in CSV.
import pandas as pd
# Read a CSV file from disk
df = pd.read_csv('data/sales.csv')
print(df.shape)
print(df.head())Basic read_csv() Call
The only required argument is the file path (string or Path object). By default Pandas assumes the first row is the header (column names), the delimiter is a comma, and values are inferred to appropriate dtypes. The resulting DataFrame has a default integer RangeIndex. Always call df.info() immediately after loading to spot type inference issues.
import pandas as pd
df = pd.read_csv('products.csv')
# Equivalent with explicit defaults:
df = pd.read_csv('products.csv',
sep=',',
header=0,
index_col=None)Controlling the Delimiter
Use the sep= parameter to specify a non-comma delimiter. Tab-separated files (TSV) use sep='\t'. Some European exports use semicolons as separators (sep=';') because commas are used as decimal separators. Pass sep=None, engine='python' to let Pandas auto-detect the separator from the file content.
import pandas as pd
# Tab-separated file
df_tsv = pd.read_csv('data.tsv', sep='\t')
# Semicolon-separated (common in Europe)
df_semi = pd.read_csv('data.csv', sep=';')
# Auto-detect separator
df_auto = pd.read_csv('data.txt', sep=None, engine='python')Header and skiprows
If a CSV has no header row, set header=None and Pandas will assign integer column names (0, 1, 2, ...). Provide custom names with names=['a', 'b', 'c']. Use skiprows=n to skip the first n rows (for metadata or comments at the top of the file). skiprows also accepts a list of specific row numbers to skip.
import pandas as pd
# CSV with no header
df = pd.read_csv('noheader.csv', header=None,
names=['id', 'value', 'category'])
# Skip first 3 rows (e.g., metadata or comments)
df = pd.read_csv('report.csv', skiprows=3)Setting the Index Column
index_col= specifies which column to use as the row index. Pass a column name or integer position. Setting a meaningful index (e.g., a date column or a unique ID) enables fast label-based access with .loc and is required before time-series operations. Pass a list for a MultiIndex.
import pandas as pd
# Use 'date' column as row index
df = pd.read_csv('timeseries.csv', index_col='date', parse_dates=True)
print(df.index.dtype) # datetime64[ns]
# Equivalent with column position
df2 = pd.read_csv('timeseries.csv', index_col=0, parse_dates=True)Parsing Dates on Load
parse_dates=True tells Pandas to try converting the index to datetime. Pass a list of column names to parse_dates=['col1', 'col2'] to parse specific non-index columns as dates. Pandas will try common formats automatically; for unusual formats use date_format=. Parsing dates at load time avoids repeated pd.to_datetime() calls later.
import pandas as pd
# Parse 'order_date' column as datetime
df = pd.read_csv('orders.csv',
parse_dates=['order_date'])
print(df['order_date'].dtype) # datetime64[ns]Selecting Columns with usecols
usecols=['col1', 'col2'] loads only the specified columns, ignoring all others. This is critical for large CSV files — there is no need to read a 200-column file if you only need 5 columns. It reduces both I/O time and memory usage significantly. Pass a callable to select columns by a name pattern.
import pandas as pd
# Load only 3 of potentially many columns
df = pd.read_csv('big_file.csv',
usecols=['user_id', 'event', 'timestamp'])
print(df.columns.tolist()) # ['user_id', 'event', 'timestamp']Controlling dtypes on Load
Pandas infers dtypes, but inference can be wrong — an ID column of all-numeric strings becomes int64, or a price column with missing values becomes float64 unexpectedly. Use dtype={'col': str} to enforce types. This is also more efficient: pre-specifying dtypes skips the inference pass and can speed up loading large files by 20-30%.
import pandas as pd
df = pd.read_csv('orders.csv', dtype={
'order_id': str, # keep as string (not int)
'price': float,
'quantity': 'int32' # use smaller int
})Handling Missing Values on Load
By default Pandas recognises many missing value representations: empty cells, 'NA', 'NaN', 'N/A', 'null', etc. Use na_values=['?', '-', 'missing'] to add custom tokens. Use keep_default_na=False to disable the built-in list and only treat the values you specify as missing. This prevents accidentally treating legitimate string values like 'NA' (an acronym) as NaN.
import pandas as pd
df = pd.read_csv('survey.csv',
na_values=['?', '', 'N/A', 'none'])
print(df.isnull().sum())nrows and chunksize for Large Files
nrows=100 loads only the first 100 rows — perfect for a quick schema check on a massive file. chunksize=10000 returns a TextFileReader iterator that yields DataFrames of 10000 rows each, enabling chunked processing of files that do not fit in RAM. Chunked reading is covered in depth in the advanced performance lesson.
import pandas as pd
# Quick peek at a large file
header_df = pd.read_csv('huge.csv', nrows=5)
print(header_df.dtypes)
# Chunked reading
for chunk in pd.read_csv('huge.csv', chunksize=50000):
print(chunk.shape) # process each chunkCommon Gotchas with read_csv
Watch out for these frequent issues: encoding errors (use encoding='utf-8' or 'latin-1'), leading spaces in column names (use skipinitialspace=True), thousands separators in numbers (use thousands=','), and decimal commas in European numbers (use decimal=',' and sep=';'). Each of these silently turns numeric columns into objects if ignored.
import pandas as pd
# European format: semicolon sep, comma decimal, UTF-8
df = pd.read_csv('euro_data.csv',
sep=';',
decimal=',',
thousands='.',
encoding='utf-8',
skipinitialspace=True)Quick Check
Test your understanding of reading CSV files with Pandas from this lesson.
Lesson Recap
In this lesson you learned: pd.read_csv() is the primary function for loading tabular data with many configuration parameters, sep, header, index_col, and parse_dates control how the file is interpreted, and usecols and dtype improve performance and type safety for large files. Next up we read Excel and JSON files, which have their own format-specific parameters.
Frequently asked questions
Is the “Reading CSV Files” lesson free?
Yes — the full text of “Reading CSV Files” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “Reading CSV Files”?
Load CSV files with pd.read_csv, control delimiters, header rows, and index columns, and preview the result. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Reading CSV Files” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.