0Pricing
Pandas & NumPy Academy · Lesson

Writing DataFrames to Files

Export a cleaned DataFrame to CSV and Excel with to_csv and to_excel, controlling the index and float format.

Writing DataFrames to Files is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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 title

Writing 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 exactly

Quick 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.

Frequently asked questions

Is the “Writing DataFrames to Files” lesson free?

Yes — the full text of “Writing DataFrames to Files” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.

What will I learn in “Writing DataFrames to Files”?

Export a cleaned DataFrame to CSV and Excel with to_csv and to_excel, controlling the index and float format. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Pandas & NumPy Academy?

No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Writing DataFrames to Files” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Pandas & NumPy Academy lesson?

Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Reading CSV Files
  2. Reading Excel and JSON Files
  3. Writing DataFrames to Files
  4. Reading from URLs and StringIO
← Back to Pandas & NumPy Academy