Pandas pd.ead_csv() function
read_csv() is the most commonly used data-reading function in the pandas library, used to read data from a CSV (comma-separated values) file and create a DataFrame.
A CSV file is a simple and widely used data exchange format that stores tabular data as plain text, with each line representing a record and fields separated by commas.read_csv() can intelligently parse CSV files, automatically detect column names and data types, and handle various delimiters and encoding issues.
Basic syntax and parameters
Syntax format
pandas.read_csv(filepath_or_buffer, sep=',', delimiter=None, header='infer',
names=None, index_col=None, usecols=None, dtype=None,
skiprows=None, nrows=None, na_values=None, ...)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| filepath_or_buffer | str, path object, or file-like object | the path, URL, or file object of the CSV file | Required |
| sep | str | the field delimiter; the CSV default is a comma | ',' |
| header | int, list of int, 'infer' | the row number to use as column names; 0 means the first row | 'infer' |
| names | list-like | a custom list of column names | None |
| index_col | int, str, list of int, list of str, False | Column used as the row index | None |
| usecols | list-like, callable | read only the specified columns | None |
| dtype | dict | specify column data types, e.g., {'a': np.float64} | None |
| skiprows | list-like, int | skip the specified rows | None |
| nrows | int | read only the first n rows | None |
| na_values | scalar, str, list-like, dict | values to be recognized as NA/NaN | None |
| encoding | str | the file encoding, e.g., 'utf-8' | None |
Return Value
- Return Type:
pd.DataFrame - returns a two-dimensional labeled data structure, namely a pandas DataFrame, on which various data analysis and processing operations can be performed.
Example
Through the following examples, fully master read_csv() its various usages.
Example 1: read a local CSV file
First create a simple CSV file, then use read_csv() to read it.
Example
import
pandas
as
pd
Create a sample CSV file
First write some test data
data
=
"""name,age,city,salary
Tom,28,Beijing,8000
Jerry,35,Shanghai,12000
Mike,42,Guangzhou,15000
Lucy,26,Shenzhen,7000
"""
Write the data to a file (in practice you can read an existing file directly)
with
open
(
'employees.csv'
,
'w'
,
encoding
=
'utf-8'
)
as
f:
f.
write
(
data
)
Read the CSV file using read_csv
filepath_or_buffer: file path (required)
df
=
pd.
read_csv
(
'employees.csv'
)
View the reading result
(
"DataFrame read:"
)
(
df
)
(
"ndata types:"
)
(
df.
dtypes
)
(
"ncolumn names:"
,
df.
columns
.
tolist
(
)
)
Expected output:
读取的 DataFrame:
name age city salary
0 Tom 28 Beijing 8000
1 Jerry 35 Shanghai 12000
2 Mike 42 Guangzhou 15000
3 Lucy 26 Shenzhen 7000
Data type:
name object
age int64
city object
salary int64
列名: ['name', 'age', 'city', 'salary']
Code analysis:
pd.read_csv('employees.csv')is the most basic usage; simply pass in the file path.- By default, the first row is automatically recognized as the column names (header='infer').
- pandas automatically infers the data type of each column: strings become object, integers become int64.
- The returned DataFrame can be viewed directly with
print(), or used for further data analysis.
Example 2: custom column names and selecting specific columns
In real work, we may need to customize column names or read only some columns to improve performance.
Example
import
pandas
as
pd
Create test data
data
=
"""name,age,city,salary,department
Tom,28,Beijing,8000,IT
Jerry,35,Shanghai,12000,HR
Mike,42,Guangzhou,15000,Sales
Lucy,26,Shenzhen,7000,IT
"""
with
open
(
'employees2.csv'
,
'w'
,
encoding
=
'utf-8'
)
as
f:
f.
write
(
data
)
Example 2a: custom column names
The names parameter specifies new column names and overrides those in the original file
df_custom
=
pd.
read_csv
(
'employees2.csv'
,
names
=
[
'Name'
,
'Age'
,
'City'
,
'Salary'
,
'Department'
]
,
header
=
0
)
(
"DataFrame with custom column names:"
)
(
df_custom
)
(
)
Example 2b: read only the specified columns
The usecols parameter lets you specify which columns to read, improving performance
df_partial
=
pd.
read_csv
(
'employees2.csv'
,
usecols
=
[
'name'
,
'salary'
]
)
(
"only some columns read:"
)
(
df_partial
)
(
)
Example 2c: use index_col to specify an index column
df_indexed
=
pd.
read_csv
(
'employees2.csv'
,
index_col
=
'name'
)
(
"set name as the index:"
)
(
df_indexed
)
Expected output:
自定义列名后的 DataFrame:
姓名 年龄 城市 薪资 部门
0 Tom 28 Beijing 8000 IT
1 Jerry 35 Shanghai 12000 HR
2 Mike 42 Guangzhou 15000 Sales
3 Lucy 26 Shenzhen 7000 IT
# Only read a subset of columns:
name salary
0 Tom 8000
1 Jerry 12000
2 Mike 15000
3 Lucy 7000
Set name as index:
age city salary department
name
Tom 28 Beijing 8000 IT
Jerry 35 Shanghai 12000 HR
Mike 42 Guangzhou 15000 Sales
Lucy 26 Shenzhen 7000 IT
Code analysis:
namesThe parameter must match the number of data columns; if the file has a header row, you can setheader=0to use the original header.usecolsYou can pass a list of column names (recommended) or a list of column indexes; the returned columns follow the specified order.index_colSetting a column as the row index makes later index-based lookups fast.
Example 3: handling special data and improving missing-value handling
A CSV file may contain missing values, use special delimiters, or require skipping certain rows.
Example
import
pandas
as
pd
Create a CSV file containing special data
Use a semicolon as the delimiter, including missing values and NA values
data
=
"""name;age;city;salary
Tom;28;Beijing;8000
Jerry;;Shanghai;12000
Mike;42;Guangzhou;
Lucy;26;NA;7000
"""
with
open
(
'employees3.csv'
,
'w'
,
encoding
=
'utf-8'
)
as
f:
f.
write
(
data
)
Example 3a: read a semicolon-delimited file
df_semicolon
=
pd.
read_csv
(
'employees3.csv'
,
sep
=
';'
)
(
"using the semicolon delimiter:"
)
(
df_semicolon
)
(
"missing value statistics:"
)
(
df_semicolon.
isnull
(
)
)
(
)
Example 3b: specify which values are treated as missing
df_na
=
pd.
read_csv
(
'employees3.csv'
,
sep
=
';'
,
na_values
=
[
'NA'
,
'missing'
]
)
(
"after custom NA values:"
)
(
df_na
)
(
)
Example 3c: skip rows and limit the number of rows read
If the first few lines of the file are comments, you can skip them
data_with_comment
=
"""# This is an employee data file
Created: 2024-01-01
name;age;city;salary
Tom;28;Beijing;8000
Jerry;35;Shanghai;12000
Mike;42;Guangzhou;15000
Lucy;26;Shenzhen;7000
"""
with
open
(
'employees4.csv'
,
'w'
,
encoding
=
'utf-8'
)
as
f:
f.
write
(
data_with_comment
)
skiprows skips the first two lines (comment lines)
df_skip
=
pd.
read_csv
(
'employees4.csv'
,
sep
=
';'
,
skiprows
=
2
)
(
"after skipping comment lines:"
)
(
df_skip
)
(
)
nrows reads only the first 3 rows
df_nrows
=
pd.
read_csv
(
'employees4.csv'
,
sep
=
';'
,
skiprows
=
2
,
nrows
=
3
)
(
"only the first 3 rows read:"
)
(
df_nrows
)
Expected output:
Using semicolon separator:
name age city salary
0 Tom 28.0 Beijing 8000.0
1 Jerry NaN Shanghai 12000.0
2 NaN 42.0 Guangzhou NaN
3 Lucy 26.0 NA 7000.0
Missing value statistics:
name age city salary
0 False False False False
1 False True False False
2 True False False True
3 False False False False
After customizing NA values:
name age city salary
0 Tom 28.0 Beijing 8000.0
1 Jerry NaN Shanghai 12000.0
2 NaN 42.0 Guangzhou NaN
3 Lucy 26.0 NaN 7000.0
After skipping comment lines:
name age city salary
0 Tom 28 Beijing 8000
1 Jerry 35 Shanghai 12000
42 Guangzhou 15000
2 Mike
3 Lucy 26 Shenzhen 7000
Only read the first 3 lines:
name age city salary
0 Tom 28 Beijing 800本地
1 Jerry 35 Shanghai 12000
2 Mike 42 Guangzhou 15000
Code analysis:
sepThe parameter can specify any delimiter, such as a semicolon, tab, etc.- By default, empty strings, spaces, etc. are recognized as missing values. You can use the
na_valuesparameter to customize which values are treated as NA. skiprowsYou can skip a specified number of lines at the beginning of a file, which is convenient for files with comments.nrowsLimit the number of rows read, suitable for chunked reading of large files.
Notes
- When reading large files, consider using the
chunksizeparameter to read in chunks and avoid running out of memory. - When handling Chinese files, you need to correctly specify the
encodingparameter; common encodings include 'utf-8', 'gbk', 'gb2312', etc. - If the CSV file has no header row, you need to set
header=None, and then use thenamesparameter to specify column names. - For non-standard CSV files, you may need to adjust
sep、quotecharand other parameters to parse them correctly.
Summary
read_csv() is the most basic and most important data-reading function in pandas. It is powerful, supporting multiple delimiters, custom column names, index settings, missing-value handling, and other advanced features.
In real data analysis work, mastering read_csv() and its various parameters lets you efficiently handle CSV files in various formats, laying a solid foundation for subsequent data cleaning and analysis. Readers are encouraged to practice more and master these common parameters.
Common Pandas functions