Pandas df.to_parquet() Function
to_parquet() It is a DataFrame method used to export data to a Parquet format file.
Parquet is a columnar storage file format designed specifically for big data analytics scenarios. It offers advantages such as high compression ratios, high read/write performance, and support for complex data types, making it the standard format for big data frameworks like Apache Hadoop and Apache Spark.
Basic syntax and parameters
Syntax format
DataFrame.to_parquet(path, engine='auto', compression='snappy',
index=None, partition_cols=None, storage_options=None, ...)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| path | str, path object | File path | Required |
| engine | str | Engines: 'auto', 'pyarrow', 'fastparquet' | 'auto' |
| compression | str | Compression: 'snappy', 'gzip', 'brotli', None | 'snappy' |
| index | bool, None | Whether to include the index | None |
| partition_cols | list | Partition columns; store data partitioned by column | None |
Return value description
- Return Type:
None - Writes data directly to a Parquet file, with no return value.
Example
Through the following examples, fully master to_parquet() its various usages.
Example 1: Basic Usage - Exporting to a Parquet File
First create a DataFrame, then use to_parquet() Export to a Parquet file.
Example
import
pandas
as
pd
Create a sample DataFrame
data
=
{
'name'
:
[
'Tom'
,
'Jerry'
,
'Mike'
,
'Lucy'
,
'John'
]
,
'age'
:
[
28
,
35
,
42
,
26
,
31
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
,
'Hangzhou'
]
,
'salary'
:
[
8000
,
12000
,
15000
,
7000
,
9000
]
,
'department'
:
[
'IT'
,
'HR'
,
'Sales'
,
'IT'
,
'HR'
]
}
df
=
pd.
DataFrame
(
data
)
Example 1a: Basic export
path: file path (required)
Use snappy compression by default
df.
to_parquet
(
'employees.parquet'
)
(
"Exported to employees.parquet"
)
View the file size
import
os
file_size
=
os
.
path
.
getsize
(
'employees.parquet'
)
(
f
"File size: {file_size} bytes"
)
Example 1b: Read back to verify
Need to install pyarrow or fastparquet
df_check
=
pd.
read_parquet
(
'employees.parquet'
)
(
"nVerify read:"
)
(
df_check
)
Result:
已导出到 employees.parquet
文件大小: 约 600-800 字节(远小于 CSV)
Verify reading:
name age city salary department
0 Tom 28 Beijing 8000 IT
1 Jerry 35 Shanghai 12000 HR
2 Mike 42 Guangzhou 15000 Sales
3 Lucy 26 Shenzhen 7000 IT
4 John 31 Hangzhou 9000 HR
Code analysis:
to_parquet()Export the DataFrame to Parquet format.- Use
snappycompression by default, which is very effective. - Parquet files are much smaller than CSV files and read faster too.
Example 2: Choosing the Engine and Compression
The Parquet format supports multiple engines and compression methods, which can be chosen as needed.
Example
import
pandas
as
pd
import
os
Create a larger DataFrame to observe the compression effect
import
numpy
as
np
np.
random
.
seed
(
42
)
df_large
=
pd.
DataFrame
(
{
'id'
:
range
(
10000
)
,
'value'
: np.
random
.
randn
(
10000
)
,
'category'
: np.
random
.
choice
(
[
'A'
,
'B'
,
'C'
,
'D'
]
,
10000
)
,
'name'
: np.
random
.
choice
(
[
'Tom'
,
'Jerry'
,
'Mike'
,
'Lucy'
,
'John'
]
,
10000
)
}
)
Example 2a: Using different compression methods
snappy: fast compression, high speed, moderate compression ratio (default)
df_large.
to_parquet
(
'output_snappy.parquet'
,
compression
=
'snappy'
)
gzip: high compression ratio, smaller files
df_large.
to_parquet
(
'output_gzip.parquet'
,
compression
=
'gzip'
)
brotli: an even higher compression ratio
df_large.
to_parquet
(
'output_brotli.parquet'
,
compression
=
'brotli'
)
No compression
df_large.
to_parquet
(
'output_none.parquet'
,
compression
=
None
)
Compare file sizes
(
"Comparison of file sizes for different compression methods:"
)
for
name
in
[
'snappy'
,
'gzip'
,
'brotli'
,
'none'
]
:
size
=
os
.
path
.
getsize
(
f
'output_{name}.parquet'
)
(
f
" {name}: {size:,} bytes"
)
(
)
Example 2b: Choosing the engine
auto: automatic selection (default)
pyarrow: Apache Arrow implementation, full-featured and performant
fastparquet: pure Python implementation with good compatibility
(
"Available engines: auto, pyarrow, fastparquet"
)
(
"Currently used:"
,
end
=
" "
)
Check available engines
try
:
import
pyarrow
(
"pyarrow"
)
except
ImportError
:
pass
try
:
import
fastparquet
(
"fastparquet"
)
except
ImportError
:
pass
Result:
Comparison of file sizes using different compression methods:
snappy: 约 100KB
gzip: 约 80KB
brotli: 约 70KB
none: 约 200KB
Different compression methods have their own advantages and disadvantages:
snappy: 速度快,压缩比适中(默认推荐)
gzip: 压缩比更高,适合存储
brotli: 最高压缩比,适合冷数据
none: 无压缩,速度最快
Code analysis:
compressionThe parameter can select different compression methods.snappyIt is the default option, balancing speed and compression ratio.gzipIt has a higher compression ratio but is slightly slower.engineThe parameter can select which engine to use.
Example 3: Partitioned Storage
Parquet supports partitioned storage by column, an important feature in big data analytics.
Example
import
pandas
as
pd
import
os
import
shutil
Create DataFrame
df
=
pd.
DataFrame
(
{
'name'
:
[
'Tom'
,
'Jerry'
,
'Mike'
,
'Lucy'
,
'John'
,
'Mary'
,
'Bob'
,
'Alice'
]
,
'age'
:
[
28
,
35
,
42
,
26
,
31
,
29
,
38
,
24
]
,
'department'
:
[
'IT'
,
'HR'
,
'Sales'
,
'IT'
,
'HR'
,
'IT'
,
'Sales'
,
'HR'
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
,
'Hangzhou'
,
'Beijing'
,
'Shanghai'
,
'Beijing'
]
}
)
Example 3a: Partitioning by a single column
partition_cols specifies the partition columns and generates subdirectories
if
os
.
path
.
exists
(
'partitioned'
)
:
shutil
.
rmtree
(
'partitioned'
)
df.
to_parquet
(
'partitioned'
,
partition_cols
=
[
'department'
]
)
(
"Exported partitioned by department"
)
View the partition directory structure
for
root
,
dirs
,
files
in
os
.
walk
(
'partitioned'
)
:
level
=
root.
replace
(
'partitioned'
,
''
)
.
count
(
os
.
sep
)
indent
=
' '
2
- level
(
f
'{indent}{os.path.basename(root)}/'
)
subindent
=
' '
2
(
level +
1
)
for
file
in
files:
(
f
'{subindent}{file}'
)
Result:
已按 department 分区导出
Partitioned directory structure:
partitioned/
department=HR/
xxx.parquet
department=IT/
xxx.parquet
department=Sales/
xxx.parquet
Code analysis:
partition_colsThe parameter stores data partitioned by the specified columns.- Partitioned storage creates subdirectories in the file system, one directory per partition value.
- Partitioned storage is very beneficial for big data queries, allowing you to read only the needed partitions.
Example 4: Handling the Index
When exporting to Parquet, you can choose whether to include the index.
Example
import
pandas
as
pd
Create a DataFrame with an index
df
=
pd.
DataFrame
(
{
'name'
:
[
'Tom'
,
'Jerry'
,
'Mike'
,
'Lucy'
]
,
'age'
:
[
28
,
35
,
42
,
26
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
]
}
)
df.
index
=
[
'A001'
,
'A002'
,
'A003'
,
'A004'
]
Example 4a: Include the index by default
df.
to_parquet
(
'with_index.parquet'
)
(
"Export (index included by default)"
)
Example 4b: Do not include the index
df.
to_parquet
(
'without_index.parquet'
,
index
=
False
)
(
"Export (without index)"
)
Example 4c: Explicitly include the index
df.
to_parquet
(
'explicit_index.parquet'
,
index
=
True
)
(
"Export (explicitly include index)"
)
Read and compare
(
"nRead and compare differences:"
)
(
"nOriginal data:"
)
(
df
)
(
"nRead with_index.parquet:"
)
(
pd.
read_parquet
(
'with_index.parquet'
)
)
(
"nRead without_index.parquet:"
)
(
pd.
read_parquet
(
'without_index.parquet'
)
)
(
"nRead explicit_index.parquet:"
)
(
pd.
read_parquet
(
'explicit_index.parquet'
)
)
Result:
导出(默认包含索引)
导出(不包含索引)
导出(显式包含索引)
Read and compare differences:
Original data:
name age city
A001 Tom 28 Beijing
A002 Jerry 35 Shanghai
A003 Mike 42 Guangzhou
A004 Lucy 26 Shenzhen
读取 with_index.parquet:
name age city index
0 Tom 28 Beijing A001
1 Jerry 35 Shanghai A002
2 Mike 42 Guangzhou A003
3 Lucy 26 Shenzhen A004
读取 without_index.parquet:
name age city
0 Tom 28 Beijing
1 Jerry 35 Shanghai
2 Mike 42 Guangzhou
3 Lucy 26 Shenzhen
读取 explicit_index.parquet:
name age city index
0 Tom 28 Beijing A001
1 Jerry 35 Shanghai A002
2 Mike 42 Guangzhou A003
3 Lucy 26 Shenzhen A004
Code analysis:
index=TrueExplicitly include the index as a column.index=FalseDo not include the index.- The default behavior depends on pandas' index settings.
Notes
- Use
to_parquet()Installation requiredpyarroworfastparquet。 - Recommended installation
pyarrow:pip install pyarrow。 - Parquet is a columnar storage format, suitable for big data analytics and not for small data.
- Partitioned storage can significantly improve big data query performance.
- Parquet supports complex data types (nested structures), but they are not commonly used with pandas DataFrames.
Summary
to_parquet() is the method for exporting a DataFrame to the Parquet format. Parquet is the standard columnar storage format in big data, offering advantages such as a high compression ratio, high performance, and support for partitioning.
In big data processing, Parquet is the preferred data format. It is fully compatible with big data frameworks such as Apache Spark and Apache Hive. When working with large-scale data, it is recommended to use Parquet instead of CSV or Excel.
Common Pandas functions