Sub topic 1
Which format should you save to?
Before you call to_csv, to_excel, or to_parquet, decide which file you need. The three formats solve different problems. A wrong choice shows up later as lost dtypes, a file too big to open, or a colleague who cannot read your output.
This chapter gives you a way to choose. The later chapters cover each writer in detail.
Prerequisites
This chapter assumes you can:
- Run Python scripts or notebooks.
- Create and inspect a pandas DataFrame, including
df.dtypesanddf.info(). - Install packages with
pip. - Recognise column dtypes: integer, float, string (object), datetime, and category.
You need pandas for everything below. The Excel and Parquet writers need extra packages, which pandas does not install for you:
pip install pandas openpyxl pyarrowopenpyxllets pandas write.xlsxfiles.pyarrowis the usual Parquet engine.fastparquetis an alternative, and pandas uses whichever it finds.
The three formats in one picture
Each format stores the same table in a different way.
- CSV (comma-separated values) is plain text. Each row is a line, and each cell is separated by a delimiter. The file has no schema. It does not record that a column is an integer or a date.
- Excel (
.xlsx) is a zipped bundle of XML files. It holds sheets, cell types, and formatting. People can open and edit it with a spreadsheet program. - Parquet is a binary, column-oriented format. It stores a schema with the data and compresses by column. Spreadsheet programs do not open it, but data tools such as pandas, Spark, DuckDB, and BigQuery read it directly.
| Property | CSV | Excel (.xlsx) | Parquet |
|---|---|---|---|
| Human-readable in a text editor | Yes | No | No |
| Opens in a spreadsheet | Yes | Yes | No |
| Stores column dtypes | No | Partly (number, text, date) | Yes |
| Stores multiple tables in one file | No | Yes (sheets) | No (one table per file or dataset) |
| Row limit | None | 1,048,576 per sheet | None practical |
| Typical size for the same data | Large | Medium | Small |
| Read and write speed on large data | Slow | Slowest | Fast |
| Extra packages in pandas | None | `openpyxl` | `pyarrow` or `fastparquet` |
A decision path
Ask three questions in order: who reads the file, how big is the data, and do the dtypes need to survive?
Choose CSV when interoperability matters most
CSV is the lowest common denominator. Almost every language, database, and tool can read it. You can inspect it with head, diff it in version control, and fix it by hand.
Use CSV when:
- The receiver is unknown or uses old software.
- The file is small or moderate in size.
- You want a file that a person or script can read without special libraries.
The cost is that CSV discards type information, as shown below.
Choose Excel when the audience works in spreadsheets
Excel is the right choice when a person will open the file, filter it, and perhaps add formulas. It can hold several sheets in one workbook, such as raw data and a summary. It can also carry light formatting like frozen header rows and column widths.
Use Excel when:
- The reader is a business user, not a developer.
- The data fits within the sheet limits (see below).
- You want one file with several related tables.
Do not use Excel as an exchange format between programs. It is slow to write, and the numbers inside can lose precision.
Choose Parquet when the next reader is code
Parquet keeps the schema with the data. A datetime column comes back as datetime, and a category comes back as a category. It is compressed by default, so files are usually much smaller than the same CSV, and reading a subset of columns is fast because each column is stored separately.
Use Parquet when:
- Another script, notebook, or data tool will load the file.
- The data is large, or you write it repeatedly.
- You need exact dtypes without re-declaring them on every read.
See the difference on your own data
Run this script to write one DataFrame in all three formats, compare file sizes, and compare the dtypes that come back. The DataFrame has 50,000 rows, which is small enough that the Excel write finishes in a few seconds.
import os
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 50_000
df = pd.DataFrame({
"order_id": np.arange(n),
"country": pd.Categorical(rng.choice(["DE", "FR", "ES", "IT"], size=n)),
"amount": rng.normal(50, 10, size=n).round(2),
"ordered_at": pd.date_range("2026-01-01", periods=n, freq="min"),
})
df.to_csv("sample.csv", index=False)
df.to_excel("sample.xlsx", index=False)
df.to_parquet("sample.parquet", index=False)
for path in ["sample.csv", "sample.xlsx", "sample.parquet"]:
print(f"{path:16} {os.path.getsize(path) / 1024:8.0f} KB")
print()
print("Original:")
print(df.dtypes)
print()
print("From CSV:")
print(pd.read_csv("sample.csv").dtypes)
print()
print("From Parquet:")
print(pd.read_parquet("sample.parquet").dtypes)What to look for in the output:
- The Parquet file is normally the smallest, and the CSV is the largest or close to it. Exact sizes depend on your data and library versions.
- The CSV read-back shows
countryandordered_atasobject.read_csvhas no way to know the original dtypes. Both columns come back as plain strings. - The Parquet read-back matches the original:
categoryforcountryanddatetime64[ns]forordered_at. Depending on your pandas version, the datetime resolution may show asnsor another unit.
The index=False argument keeps the DataFrame's row index out of the file. The next chapters explain it and the other options.
What each format loses or limits
CSV
- No dtypes. Everything is text on disk. On reading, pandas guesses the dtypes. Dates stay as strings unless you pass
parse_dates. Categories come back as strings. - Ambiguous missing values. An empty cell,
NA, and an empty string can all mean different things. Only a convention that both sides agree on keeps them apart. - Locale clashes. In many European locales the delimiter is
;and the decimal separator is,. A file written with defaults may open as one garbled column in such a spreadsheet. - Encoding. pandas writes UTF-8 by default. Older tools may expect another encoding and show accented characters incorrectly.
Excel
- Sheet limits. An
.xlsxsheet holds at most 1,048,576 rows and 16,384 columns. Writing more raises an error or requires splitting the data across sheets. - Precision. Excel stores numbers as 64-bit floats and displays about 15 significant digits. Long identifiers such as 18-digit IDs should be written as text.
- Silent conversions. Opening a CSV in Excel can change values, for example turning
0012into12or a gene name likeSEPT2into a date. Writing a real.xlsxfile with typed cells avoids this, because the types are stored in the file. - Cost. Writing is slow and memory-hungry compared with the other two formats.
Parquet
- Not for people. You cannot open it in a text editor or a spreadsheet.
- Column names must be strings. A DataFrame with integer column labels raises an error in
to_parquet. Convert them first withdf.columns = df.columns.astype(str). - Mixed-type columns fail. An
objectcolumn that holds both numbers and strings cannot be written, because Parquet needs one type per column. - A dependency is required. Without
pyarroworfastparquet,to_parquetraises anImportError. - Some pandas objects need care. Arbitrary Python objects in an
objectcolumn are not stored in a portable way. A later chapter covers what Parquet cannot store.
Combining formats
You do not have to pick only one. A common pattern is to keep the working copy in Parquet and produce other formats for specific readers.
- Store the cleaned dataset as Parquet. It is the source of truth, with exact dtypes and small size.
- Export a CSV for systems that need a plain-text feed.
- Export an Excel workbook with a summary sheet for the people who will read the results.
Each export is a different view of the same DataFrame. The Parquet file is the one you reload when you need the data back unchanged.
Common mistakes when choosing
- Using CSV for intermediate results in a pipeline. Every reload re-parses text and re-infers dtypes. Dates become strings and integer columns with missing values become floats. Use Parquet between steps.
- Sending Parquet to a non-technical colleague. They cannot open it. Ask what tool they use first.
- Using Excel for large data. Hitting the row limit is a hard stop, and slow writes make it worse well before that.
- Assuming the extension decides the format. pandas picks the writer from the method you call.
df.to_csv("data.xlsx")writes a CSV with the wrong extension, and Excel will complain when it opens it.
Checklist before you write
- Who or what reads this file next?
- Do the dtypes need to survive the trip?
- How many rows and columns will it have?
- Which optional package does the format need, and is it installed?
- Will you verify the result by reading it back? A later chapter shows how.
Exercise
A data engineer writes a daily 8-million-row DataFrame with a datetime column and a category column. Another Python job loads it every morning. A manager also wants a one-page summary she can filter in a spreadsheet. Which formats would you use for the two readers, and why?
Show answer
Use Parquet for the full 8-million-row dataset. The next reader is code, the data is large, and Parquet keeps the datetime and category dtypes without extra arguments. Excel and CSV would be slower and larger, and they would lose the dtypes. Use Excel for the manager's summary, written as a small aggregated DataFrame with to_excel. It is far below the 1,048,576-row limit, and a spreadsheet user can filter it directly. Do not give her the 8-million-row table in Excel, because it exceeds the sheet limit.
Exercise
You run pd.read_csv("sample.csv") on a file written from a DataFrame with a datetime column. df.dtypes shows object for that column. Why does this happen, and which format would avoid it without extra read arguments?
Show answer
CSV stores only text and no schema, so read_csv cannot tell that the strings are dates and leaves them as object. Passing parse_dates=["column_name"] restores the dtype. Parquet avoids the problem because it stores the schema with the data, so read_parquet returns a datetime column directly.