Pandas df.to_csv() Function
to_csv() It is a DataFrame method used to export data to a file in CSV (comma-separated values) format.
CSV is one of the most commonly used data export formats; it stores tabular data as plain text, is highly compatible, and can be read by almost all data analysis tools.to_csv() It is feature-rich, supporting custom delimiters, encodings, index handling, and other options to meet various export needs.
Basic syntax and parameters
Syntax format
DataFrame.to_csv(path_or_buf=None, sep=',', na_rep='', float_format=None,
columns=None, header=True, index=True, index_label=None,
mode='w', encoding=None, quoting=None, quotechar='"',
line_terminator=None, chunksize=None, date_format=None,
doublequote=True, escapechar=None, ...)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| path_or_buf | str, path object, file-like object | File path; if None, return a string | None |
| sep | str | Field delimiter | ',' |
| na_rep | str | Representation of missing values | '' |
| float_format | str | Floating-point number format | None |
| columns | list | Specify which columns to export | None |
| header | bool, list | Whether to export column names | True |
| index | bool | Whether to export the index | True |
| index_label | str | Name of the index column | None |
| mode | str | Write mode: 'w' overwrite, 'a' append | 'w' |
| encoding | str | File encoding | None |
Return Value
- Return Type:
Noneorstr - When a file path is specified, write to the file and return None.
- When
path_or_buf=None, return a CSV-formatted string.
Example
Through the following examples, fully master to_csv() its various usages.
Example 1: Basic Usage - Exporting to a CSV File
First create a DataFrame, then use to_csv() to export to a CSV file.
Example
import
pandas
as
pd
Create a sample DataFrame
data
=
{
'name'
:
[
'Tom'
,
'Jerry'
,
'Mike'
,
'Lucy'
]
,
'age'
:
[
28
,
35
,
42
,
26
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
]
,
'salary'
:
[
8000
,
12000
,
15000
,
7000
]
}
df
=
pd.
DataFrame
(
data
)
Example 1a: The most basic export
path_or_buf: file path (the required parameter is the file path; here it is set to None to return a string)
csv_string
=
df.
to_csv
(
)
Without specifying a path, return a string
(
"Returned CSV string:"
)
(
csv_string
)
(
)
Export to a file
The index and column names are included by default
df.
to_csv
(
'output_basic.csv'
,
index
=
False
)
index=False does not export the index
(
"Exported to output_basic.csv"
)
Read back to verify
df_check
=
pd.
read_csv
(
'output_basic.csv'
)
(
"nVerify read:"
)
(
df_check
)
Expected output:
Returned CSV string:
,name,age,city,salary
0,Tom,28,Beijing,8000
1,Jerry,35,Shanghai,12000
2,Mike,42,Guangzhou,15000
3,Lucy,26,Shenzhen,7000
已导出到 output_basic.csv
Verify reading:
name age city salary
0 Tom 28 Beijing 8000
1 Jerry 35 Shanghai 12000
2 保存 Mike 42 Guangzhou 15000
3 Lucy 26 Shenzhen 7000
Code analysis:
to_csv()By default, the index (the first column has no name) and column names are exported.- Settings
index=FalseYou can choose not to export the index, which is more convenient when importing. - When no path is specified, a CSV-formatted string is returned.
Example 2: Custom Delimiters and Formats
CSV files can use different delimiters, and you can customize the format of numbers and missing values.
Example
import
pandas
as
pd
Create a DataFrame containing missing values and floating-point numbers
data
=
{
'name'
:
[
'Tom'
,
'Jerry'
,
'Mike'
,
'Lucy'
]
,
'age'
:
[
28
,
35
,
42
,
None
]
,
Missing Values
'score'
:
[
85.5
,
92.3
,
78.9
,
95.0
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
None
,
'Shenzhen'
]
}
df
=
pd.
DataFrame
(
data
)
Example 2a: Using a semicolon delimiter
df.
to_csv
(
'output_semicolon.csv'
,
sep
=
';'
,
index
=
False
)
(
"Export with a semicolon delimiter:"
)
with
open
(
'output_semicolon.csv'
,
'r'
)
as
f:
(
f.
read
(
)
)
(
)
Example 2b: Custom missing value representation
df.
to_csv
(
'output_na.csv'
,
index
=
False
,
na_rep
=
'N/A'
)
(
"Custom missing value representation:"
)
with
open
(
'output_na.csv'
,
'r'
)
as
f:
(
f.
read
(
)
)
(
)
Example 2c: Formatting floating-point numbers
float_format uses a Python format string
df.
to_csv
(
'output_float.csv'
,
index
=
False
,
float_format
=
'%.2f'
)
(
"Formatted floating-point numbers:"
)
with
open
(
'output_float.csv'
,
'r'
)
as
f:
(
f.
read
(
)
)
(
)
Example 2d: Exporting selected columns
df.
to_csv
(
'output_columns.csv'
,
index
=
False
,
columns
=
[
'name'
,
'score'
]
)
(
"Export specified columns:"
)
with
open
(
'output_columns.csv'
,
'r'
)
as
f:
(
f.
read
(
)
)
Expected output:
Export using semicolon delimiter:
name;age;score;city
Tom;28;85.5;Beijing
Jerry;35;92.3;Shanghai
Mike;42;78.9;Guangzhou
Lucy;;95;Shenzhen
Custom missing value representation:
name,age,score,city
Tom,28,85.5,Beijing
Jerry,35,92.3,Shanghai
Mike,42,78.9,Guangzhou
Lucy,N/A,95.0,N/A
# Format floating point numbers:
name,age,score,c列
Tom,28,85.50,Beijing
Jerry,35,92.30,Shanghai
Mike,42,78.90,encoding
Lucy,,95.00,Shenzhen
# Export specified columns:
name,score
Tom,85.5
Jerry,92.3
自定义分隔符 78.9
Lucy,95.0
Code analysis:
sepThe parameter can specify any delimiter, such as a semicolon, tab, etc.na_repThe parameter customizes the string representation of missing values, defaulting to an empty string.float_formatThe parameter uses Python's format string syntax.columnsThe parameter exports only the specified columns.
Example 3: Handling Index and Encoding
Index handling and file encoding are common requirements when exporting.
Example
import
pandas
as
pd
Create a DataFrame with an index
data
=
{
'name'
:
[
'Tom'
,
'Jerry'
,
'Mike'
,
'Lucy'
]
,
'age'
:
[
28
,
35
,
42
,
26
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
]
}
df
=
pd.
DataFrame
(
data
)
df.
index
=
[
'A001'
,
'A002'
,
'A003'
,
'A004'
]
Set the index
Example 3a: Export the index and specify the index column name
df.
to_csv
(
'output_index.csv'
,
index
=
True
,
index_label
=
'user_id'
)
(
"With index and index column name:"
)
with
open
(
'output_index.csv'
,
'r'
)
as
f:
(
f.
read
(
)
)
(
)
Example 3b: Do not export column names
df.
to_csv
(
'output_no_header.csv'
,
header
=
False
,
index
=
False
)
(
"Without column names:"
)
with
open
(
'output_no_header.csv'
,
'r'
)
as
f:
(
f.
read
(
)
)
(
)
Example 3c: Using UTF-8 encoding (supports Chinese)
df_cn
=
pd.
DataFrame
(
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
]
,
'Age'
:
[
28
,
35
,
42
]
,
'City'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
]
}
)
df_cn.
to_csv
(
'output_utf8.csv'
,
index
=
False
,
encoding
=
'utf-8-sig'
)
utf-8-sig supports opening in Excel
(
"UTF-8 encoding (with Chinese):"
)
with
open
(
'output_utf8.csv'
,
'r'
,
encoding
=
'utf-8-sig'
)
as
f:
(
f.
read
(
)
)
(
)
Example 3d: Append mode
Create the file first, then append data
df.
to_csv
(
'output_append.csv'
,
index
=
False
)
Append more data
df_append
=
pd.
DataFrame
(
{
'name'
:
[
'John'
,
'Mary'
]
,
'age'
:
[
30
,
27
]
,
'city'
:
[
'Hangzhou'
,
'Nanjing'
]
}
)
df_append.
to_csv
(
'output_append.csv'
,
index
=
False
,
mode
=
'a'
,
header
=
False
)
(
"Append mode:"
)
with
open
(
'output_append.csv'
,
'r'
)
as
f:
(
f.
read
(
)
)
Expected output:
With index and index column name:
user_id,name,age,city
A001,Tom,28,直接在
A002,Jerry,35,Shanghai
A003,Mike,42,Guangzhou
A004,Lucy,26,Shenzhen
Do not export column names:
Tom,28,Beijing
Jerry,35,Shanghai
Mike,42,Guangzhou
Lucy,26,Shenzhen
UTF-8 编码(含中文):
姓名,年龄,出现
张三,28,北京
李四,35,上海
王五,42,广州
Append mode:
Tom,28,Beijing
Jerry,35,CSV
Mike,42,Guangzhou
Lucy,26,Shenzhen
John,30,Hangzhou
Mary,27,Nanjing
追加模式 27, 格式
Code analysis:
index_labelThe parameter assigns a name to the index column.header=FalseNot exporting column names is suitable for appending and merging multiple files.encoding='utf-8-sig'Adding a BOM before UTF-8 encoding makes it convenient to open directly in Excel.mode='a'Append mode adds new data at the end of an existing file.
Notes
- The index is exported by default; if not needed, you can set
index=False。 - When handling Chinese data, remember to specify the correct encoding (recommended
utf-8-sig)。 mode='a'In append mode, note whether you also need to setheader=Falseto avoid duplicate column names.- When exporting a large DataFrame, you can use
chunksizethe parameter to write in chunks. float_formatUse Python's formatting syntax, such as'%.2f'to keep two decimal places.
Summary
to_csv() It is one of the most commonly used export methods for DataFrame and is very full-featured. It can export data to CSV files in various formats, supporting custom delimiters, encoding, index handling, and more.
In practice, CSV is a universal format for data exchange,to_csv() it is used very frequently. Readers are advised to master the usage of various parameters, especially encoding handling and index control.
Common Pandas functions