Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Data Reading and Writing

Pandas Data Reading and Writing

Pandas provides rich functions for reading and writing various data formats. Besides the commonly used CSV and Excel, it also supports SQL databases, HTML tables, Parquet, and other formats. This section introduces these supplementary I/O features to help you flexibly handle data import and export in different scenarios.


Overview of core I/O functions

Pandas' I/O capabilities are very powerful, supporting read and write operations for multiple data formats. The following are commonly used read and write functions:

Read functions Write functions Supported formats Typical scenario
pd.read_csv() to_csv() CSV、TSV Log files, tabular data
pd.read_excel() to_excel() Excel(.xlsx, .xls) Business reports, financial data
pd.read_sql() to_sql() SQL databases Enterprise database interaction
pd.read_html() - HTML Tables Web scraping
pd.read_parquet() to_parquet() Apache Parquet Big data analysis and storage
pd.read_feather() to_feather() Feather format Fast read/write, in-memory data
pd.read_json() to_json() JSON API data, Web services
pd.read_pickle() to_pickle() Python pickle Serialize Python objects

Different formats have different applicable scenarios. CSV is a general format but produces larger files; Parquet is columnar storage suitable for big data analysis; Excel is suitable for manual viewing but not for large volumes of data.


CSV and text files

CSV (Comma-Separated Values) is the most general data exchange format, and Pandas supports it most thoroughly.

Common read parameters

Example

import

pandas

as

pd

The most basic read

df

=

pd.

read_csv

(

"data.csv"

)

Specify the separator (CSV defaults to a comma, TSV to a tab)

df_tsv

=

pd.

read_csv

(

"data.tsv"

,

sep

=

"\t"

)

Specify the encoding (commonly used when handling Chinese files)

df_utf8

=

pd.

read_csv

(

"data.csv"

,

encoding

=

"utf-8"

)

df_gbk

=

pd.

read_csv

(

"data.csv"

,

encoding

=

"gbk"

)

Skip rows (skip rows after the header or comment lines)

df

=

pd.

read_csv

(

"data.csv"

,

skiprows

=

3

)

 

Skip the first 3 rows

df

=

pd.

read_csv

(

"data.csv"

,

skiprows

=

[

2

,

4

]

)

 

Skip rows 2 and 4

Use the header row (by default the first row)

df

=

pd.

read_csv

(

"data.csv"

,

header

=

0

)

 

Row 0 as the header

df

=

pd.

read_csv

(

"data.csv"

,

header

=

None

)

 

No header; automatically generate 0,1,2...

Specify column names

df

=

pd.

read_csv

(

"data.csv"

,

names

=

[

"ID"

,

"Name"

,

"Age"

,

"City"

]

)

Specify the index column

df

=

pd.

read_csv

(

"data.csv"

,

index_col

=

0

)

 

Column 0 as the index

df

=

pd.

read_csv

(

"data.csv"

,

index_col

=

[

"Name"

]

)

 

Multiple columns as a composite index

Handle missing values

Example

import

pandas

as

pd

import

numpy

as

np

Specify which values are treated as missing values

df

=

pd.

read_csv

(

   

"data.csv"

,

    na_values

=

[

"NA"

,

"null"

,

"NULL"

,

"N/A"

,

""

,

" "

]

 

These values will all be recognized as NaN

)

Different columns can use different missing-value markers

df

=

pd.

read_csv

(

   

"data.csv"

,

    na_values

=

{

       

"Age"

:

[

"File %s type is: %s%n"

,

"0"

]

,

 

Missing values for the "Age" column

       

"City"

:

[

"File %s type is: %s%n"

]

       

Missing values for the "City" column

   

}

)

Keep certain values as normal values (not recognized as missing)

df

=

pd.

read_csv

(

"data.csv"

,

keep_default_na

=

False

)

Write the CSV file

Example

import

pandas

as

pd

Prepare test data

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Wang Wu"

]

,

   

"Age"

:

[

25

,

30

,

28

]

,

   

"City"

:

[

"Beijing"

,

"Shanghai"

,

"Guangzhou"

]

}

)

Write CSV (with index by default)

df.

to_csv

(

"output.csv"

)

Do not write the index

df.

to_csv

(

"output.csv"

,

index

=

False

)

Specify a separator

df.

to_csv

(

"output.csv"

,

sep

=

"\t"

)

Do not write the header

df.

to_csv

(

"output.csv"

,

header

=

False

)

Specify the encoding

df.

to_csv

(

"output.csv"

,

encoding

=

"utf-8-sig"

)

 

With BOM, suitable for opening in Excel


JSON files

JSON (JavaScript Object Notation) is the most common data format in Web applications, and Pandas provides flexible read/write capabilities.

JSON structure and reading methods

JSON data structures come in various forms; when reading, you need to choose appropriate parameters based on the actual structure:

Example

import

pandas

as

pd

import

json

Prepare test JSON data

data_records

=

'''
[
    {"name": "Zhang San", "age": 25, "city": "Beijing"},
    {"name": "Li Si", "age": 30, "city": "Shanghai"},
    {"name": "Wang Wu", "age": 28, "city": "Guangzhou"}
]
'''

Method 1: JSON array (one object per line) -> DataFrame

df

=

pd.

read_json

(

data_records

,

orient

=

"records"

)

print

(

"orient='records':"

)

print

(

df

)

print

(

)

Method 2: JSON object (key-value pairs) -> Series

data_dict

=

'{"name": "Zhang San", "age": 25, "city": "Beijing"}'

s

=

pd.

read_json

(

data_dict

,

typ

=

"series"

)

print

(

"Read as Series:"

)

print

(

s

)

JSON Lines format

JSON Lines (.jsonl) is a format in which each line is a complete JSON object, commonly used in logging and big data scenarios:

Example

import

pandas

as

pd

JSON Lines format data

jsonl_data

=

'''{"name": "Zhang San", "age": 25}
{"name": "Li Si", "age": 30}
{"name": "Wang Wu", "age": 28}
{"name": "Zhao Liu", "age": 35}
'''

Write a JSON Lines file

with

open

(

"data.jsonl"

,

"w"

,

encoding

=

"utf-8"

)

as

f:

    f.

write

(

jsonl_data

)

Read JSON Lines (each line is a JSON object)

df

=

pd.

read_json

(

"data.jsonl"

,

lines

=

True

)

print

(

df

)

Write JSON

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Wang Wu"

]

,

   

"Age"

:

[

25

,

30

,

28

]

,

   

"City"

:

[

"Beijing"

,

"Shanghai"

,

"Guangzhou"

]

}

)

Write JSON with different orient options

df.

to_json

(

"output_records.json"

,

orient

=

"records"

,

force_ascii

=

False

,

indent

=

2

)

df.

to_json

(

"output_index.json"

,

orient

=

"index"

,

force_ascii

=

False

,

indent

=

2

)

df.

to_json

(

"output_columns.json"

,

orient

=

"columns"

,

force_ascii

=

False

,

indent

=

2

)

JSON Lines format

df.

to_json

(

"output.jsonl"

,

orient

=

"records"

,

lines

=

True

,

force_ascii

=

False

)


Pickle serialization

Pickle is Python's native object serialization format; it can save any Python object, including DataFrames and complex nested structures.

Example

import

pandas

as

pd

import

pickle

Create a DataFrame with a complex structure

df

=

pd.

DataFrame

(

{

   

"A"

:

range

(

10

)

,

   

"B"

:

range

(

10

,

20

)

,

   

"C"

:

[

"foo"

,

"bar"

]

5

}

)

Write a Pickle file

df.

to_pickle

(

"data.pkl"

)

Read a Pickle file

df_loaded

=

pd.

read_pickle

(

"data.pkl"

)

print

(

df_loaded

)

Compressed write (gzip compression, smaller file)

df.

to_pickle

(

"data.pkl.gz"

,

compression

=

"gzip"

)

df_loaded

=

pd.

read_pickle

(

"data.pkl.gz"

,

compression

=

"gzip"

)

The Pickle format can only be read by Python and is not suitable for cross-language data exchange. In addition, loading Pickle files from untrusted sources poses security risks; do not load .pkl files of unknown origin.


Performance and scenario selection

Different data formats have different performance characteristics; choosing the right format can greatly improve efficiency:

Format Read speed Write speed // Process file content Applicable scenarios
CSV Slow Medium Large General exchange format, human-readable
Parquet Very fast fast Very small Big data analysis, columnar queries
Feather Extremely fast Extremely fast Large Fast transfer of in-memory data
Pickle fast fast Medium Python object persistence
JSON Slow Medium Very big Web API, cross-language

Common Issues and Notes

1. Insufficient memory when reading large files

For very large CSV or JSON files, you can use the chunksize parameter to read in chunks, avoiding loading everything into memory at once.

2. Chinese encoding issues

When handling Chinese files, make sure to specify the correct encoding. Common encodings include utf-8, gbk, gb2312, utf-8-sig (BOM), etc.

3. File corruption after writing

Before writing important data, it is recommended to read and verify it first. Using a compressed format when writing large files can reduce disk I/O and lower the risk of data corruption.

4. Excel format limitations

Excel 2003 (.xls) supports at most 65536 rows per sheet, and the 2007 version (.xlsx) at most 1048576 rows. If you exceed the limit, consider other formats.