将 DataFrames 写入文件
使用 to_csv 和 to_excel 将清理后的 DataFrame 导出为 CSV 和 Excel 文件,并控制索引及浮点数格式。
将 DataFrames 写入文件 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Export Matters
Data analysis rarely ends inside Python. You need to share cleaned datasets with stakeholders, feed results into other tools, or archive processed data for reproducibility. Pandas provides to_csv(), to_excel(), to_json(), and to_parquet() — mirroring the read functions and accepting most of the same configuration parameters.
import pandas as pd
df = pd.DataFrame({'name': ['A', 'B'], 'score': [90, 75]})
df.to_csv('results.csv')
df.to_excel('results.xlsx')
df.to_json('results.json', orient='records')to_csv(): The Index Gotcha
By default to_csv() writes the row index as the first column, creating an unnamed: 0 column when you read the file back. Pass index=False to omit the index — almost always the right choice unless the index itself is meaningful data (like dates). Always specify index=False unless you have a deliberate reason to include the index.
import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
# Include index (default -- creates 'Unnamed: 0' when re-read)
df.to_csv('with_index.csv')
# Exclude index (recommended)
df.to_csv('clean.csv', index=False)Controlling Delimiter and Encoding
Pass sep= to write a tab-separated or semicolon-separated file. Use encoding= to specify UTF-8 or another character set — essential when column values contain non-ASCII characters like accents or Chinese characters. encoding='utf-8-sig' adds a BOM (byte-order mark) for Excel compatibility on Windows.
import pandas as pd
df = pd.DataFrame({'name': ['Müller', 'Tanaka'], 'val': [1, 2]})
# Tab-separated, UTF-8
df.to_csv('output.tsv', sep='\t', encoding='utf-8', index=False)
# Excel-compatible UTF-8 with BOM
df.to_csv('for_excel.csv', encoding='utf-8-sig', index=False)Controlling Float Formatting
By default Pandas writes floats with full precision. Use float_format='%.2f' to limit to 2 decimal places — important for financial data where extra decimal places look wrong to human readers. Pass na_rep='NULL' or na_rep='' to control how NaN values are written in the output file.
import pandas as pd
import numpy as np
df = pd.DataFrame({'price': [9.99, np.nan, 14.123456],
'qty': [1, 2, 3]})
df.to_csv('prices.csv',
index=False,
float_format='%.2f',
na_rep='N/A')to_excel(): Writing a Sheet
df.to_excel('file.xlsx', sheet_name='Data', index=False) writes the DataFrame to an Excel workbook. Like to_csv(), set index=False unless the index is meaningful. The startrow= and startcol= parameters let you position the table within the sheet — useful for adding a title row above the data.
import pandas as pd
df = pd.DataFrame({'product': ['A', 'B'], 'sales': [100, 200]})
df.to_excel('report.xlsx',
sheet_name='Sales',
index=False,
startrow=1) # leave row 0 for a titleWriting Multiple Sheets with ExcelWriter
To write multiple DataFrames to different sheets in the same workbook, use pd.ExcelWriter as a context manager. Call df.to_excel(writer, sheet_name='Name') for each DataFrame inside the with block. The workbook is finalised and saved when the context exits. This avoids creating multiple separate files for related tables.
import pandas as pd
df1 = pd.DataFrame({'a': [1, 2]})
df2 = pd.DataFrame({'b': [3, 4]})
with pd.ExcelWriter('multi_sheet.xlsx', engine='openpyxl') as writer:
df1.to_excel(writer, sheet_name='Sheet1', index=False)
df2.to_excel(writer, sheet_name='Sheet2', index=False)to_json(): Exporting JSON
df.to_json() serialises a DataFrame to JSON. The orient= parameter mirrors read_json: use 'records' for a list of row dicts (most interoperable), 'columns' for a dict of column arrays, or 'index' for a dict keyed by row label. Pass indent=2 for human-readable formatting.
import pandas as pd
df = pd.DataFrame({'name': ['A', 'B'], 'score': [90, 75]})
print(df.to_json(orient='records', indent=2))
# [
# {"name": "A", "score": 90},
# {"name": "B", "score": 75}
# ]Appending to an Existing File
To append rows to an existing CSV without overwriting, open the file in append mode using mode='a' and set header=False to avoid duplicating the header row. For Excel, use ExcelWriter with mode='a'. For large streaming pipelines, append in chunks and write the header only on the first chunk.
import pandas as pd
df_new = pd.DataFrame({'a': [5, 6], 'b': [7, 8]})
# Append to existing file, skip writing header
df_new.to_csv('existing.csv',
mode='a',
header=False,
index=False)Selecting Columns Before Export
A good practice before exporting is to select only the columns the recipient needs and to sort rows in a logical order. This makes the output file cleaner and prevents accidentally leaking internal columns like internal IDs, encoded features, or debug flags. Use bracket selection and sort_values() in the same pipeline expression before writing.
import pandas as pd
df = pd.DataFrame({'id': [3,1,2],
'name': ['C','A','B'],
'_internal': [9,7,8]})
(df[['id', 'name']]
.sort_values('id')
.to_csv('export.csv', index=False))Verifying the Written File
After writing, always read the file back and verify: check shape, column names, and a few spot values. For CI pipelines, compare checksums. For critical financial exports, assert that aggregated totals match. This catches encoding issues, float precision loss, and index problems before the file reaches a downstream consumer.
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
df.to_csv('/tmp/check.csv', index=False)
df_check = pd.read_csv('/tmp/check.csv')
assert df_check.shape == df.shape, 'Row/column count mismatch'
assert list(df_check.columns) == list(df.columns)
print('Export verified OK')Parquet: A Better Alternative for Data
For large analytical datasets, consider Parquet format instead of CSV. Parquet stores data in columnar format, supports compression, preserves dtypes exactly, and reads 10-100x faster for analytical queries. Write with df.to_parquet('data.parquet') and read with pd.read_parquet('data.parquet'). It requires pyarrow or fastparquet to be installed.
import pandas as pd
df = pd.DataFrame({'a': range(1000000), 'b': range(1000000)})
df.to_parquet('data.parquet', index=False)
df2 = pd.read_parquet('data.parquet')
print(df2.dtypes) # dtypes preserved exactlyQuick Check
Test your understanding of writing DataFrames to files from this lesson.
Lesson Recap
In this lesson you learned: to_csv() and to_excel() export DataFrames and both default to including the index — always set index=False for clean output, ExcelWriter enables writing multiple DataFrames to separate sheets in one workbook, and Parquet is a faster and more space-efficient alternative to CSV for large analytical datasets. Next up we load remote CSV files from URLs and parse in-memory CSV strings with io.StringIO.
常见问题解答
「将 DataFrames 写入文件」课时是免费的吗?
是的 — 「将 DataFrames 写入文件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。
「将 DataFrames 写入文件」这节课中我会学到什么?
使用 to_csv 和 to_excel 将清理后的 DataFrame 导出为 CSV 和 Excel 文件,并控制索引及浮点数格式。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Pandas & NumPy Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「将 DataFrames 写入文件」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?
能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 读取 CSV 文件
- 读取 Excel 与 JSON 文件
- 将 DataFrames 写入文件
- 从 URL 与 StringIO 读取