Saving a pandas DataFrame to CSV: What to_csv Changes and When to Drop the Index
How to save a pandas DataFrame to CSV, when to use index=False, what the export changes about your data, and where CSV files lose meaning after sharing.
Writing a DataFrame to a CSV file with to_csv is the standard way to get tabular data out of pandas. The most common surprise is an extra, unnamed first column in the output. That column is the DataFrame's index. This review covers what the export changes, when dropping the index is the right call, and where the resulting file can lose meaning once it leaves Python.
Short answer: is CSV export suitable for your use?
CSV is a good fit for passing tabular data to spreadsheets, databases, other languages and people who don't use Python. Its main benefit is that it is plain text that almost any tool can open. The decisive tradeoff is that CSV stores only text. It has no data types, no index semantics, no formatting and no multiple sheets. Use index=False when the index is just the default row counter (0, 1, 2 and so on). Keep the index, or convert it to a column, when it holds real data.
Plain-text CSV is preferable when readability and portability matter more than fidelity. That includes reviewing changes in version control, searching with text tools, sharing with non-Python users and keeping archives that stay readable without special software. If you will reload the data in pandas and need types such as datetimes or categoricals preserved exactly, a typed binary format such as Parquet is usually a better choice. Pickle also preserves types, but only load pickle files from sources you trust.
The basic call
import pandas as pd
df = pd.DataFrame({"id": [101, 102], "name": ["Ada", "Lin"]})
# Default: the index is written as the first column
df.to_csv("people.csv")
# Without the index
df.to_csv("people.csv", index=False)
With the default settings, the header row begins with an empty cell and every data row begins with its index value. With index=False, the file contains only the columns you defined:
# df.to_csv("people.csv")
,id,name
0,101,Ada
1,102,Lin
# df.to_csv("people.csv", index=False)
id,name
101,Ada
102,Lin
If you call to_csv without a file path, it returns the CSV content as a string. This is handy for checking the output before writing a file.
What the export actually changes
to_csv converts each cell to text, separates the values with a delimiter (a comma by default) and writes a header row of column names. The DataFrame in memory is not modified. CSV has no presentation layer, so column widths, number formats, fonts and colors are not stored. Whatever a spreadsheet displays is that application's interpretation of the text.
- Index: written as the first column unless index=False. Its header cell is blank unless the index has a name or you pass index_label.
- Types: numbers, dates, booleans and categoricals all become text. When the file is read back, types are inferred again and may not match the original.
- Missing values: NaN is written as an empty field by default. The na_rep parameter changes this.
- Floats: written at full precision unless you set float_format.
- Quoting: by default, a field is quoted only if it contains the delimiter, the quote character or a line break.
- Encoding: UTF-8 by default.
- Line endings: the operating system's default line separator unless you set lineterminator.
When to drop the index, and when not to
index=False is correct when the index is the default sequence of row numbers. If the index carries meaning, index=False silently discards it. Common examples are dates set with set_index, the group keys left by a groupby, and the labels of a pivot table. In those cases, either keep the index (optionally naming it with index_label) or move it into a regular column with reset_index before exporting.
summary = df.groupby("region")["sales"].sum() # 'region' is now the index
# Loses the region names: only the sales column is written
# summary.to_frame().to_csv("summary.csv", index=False)
# Keeps region as an ordinary column
summary.reset_index().to_csv("summary.csv", index=False)
With a MultiIndex, each index level is written as its own column, and reset_index turns all levels into ordinary columns. Multi-level column headers are written as several header rows. To rebuild them when reading the file back, pass a matching header argument to read_csv, such as header=[0, 1].
Reading the file back
Suppose a file was saved with its index and is then read with a plain read_csv call. The column with the blank header comes back as a data column named "Unnamed: 0". You can avoid this in either of two ways: write the file with index=False, or read it with index_col=0. Because types are not stored in the file, dates and identifier codes often need explicit handling on the way back in.
# File was written with the index
df2 = pd.read_csv("people.csv", index_col=0)
# Parse date columns explicitly
df3 = pd.read_csv("events.csv", parse_dates=["timestamp"])
# Keep leading zeros in codes such as ZIP codes
df4 = pd.read_csv("zips.csv", dtype={"zip": str})
TSV and other delimiters
For tab-separated output, pass sep="\t". Tabs are useful when text fields often contain commas, although quoting still applies to any field that contains a tab or a line break. Some spreadsheet setups expect semicolons instead of commas, depending on the regional list-separator setting. Check what the destination expects rather than assuming a comma will work.
df.to_csv("people.tsv", sep="\t", index=False)
df.to_csv("people_semicolon.csv", sep=";", index=False)
Will the file stay readable and usable after sharing?
Copying and pasting: because CSV is plain text, copying it keeps the characters exactly. Whether pasted text splits into separate cells depends on the receiving application and the delimiter. pandas also provides to_clipboard, which uses tab-separated output by default. Many spreadsheet applications split tab-separated text into cells when it is pasted, but confirm this in the application you actually use.
Spreadsheet reinterpretation: opening a CSV in a spreadsheet application can change how values appear. Leading zeros may be stripped, long numeric IDs may be shown in scientific notation or lose digits, and date-like strings may be converted to dates. The file itself is unchanged until someone saves it from the spreadsheet, at which point those changes become permanent. If exact values matter, don't send the file through a spreadsheet and back.
Encoding: pandas writes UTF-8 without a byte-order mark by default. Some spreadsheet software misreads non-ASCII characters in such files. Writing with encoding="utf-8-sig" adds the mark, which helps in those cases. The tradeoff is that some other tools then show a stray invisible character at the start of the first header name.
df.to_csv("people.csv", index=False, encoding="utf-8-sig")
Accessibility: a CSV file has no markup and a simple reading order of row by row, left to right. How it is announced by assistive technology depends on the application that opens it. The header row is the only labeling the file carries, so clear, descriptive column names matter, and any meaning conveyed by color or formatting in the original is lost. No scoped tests with specific screen readers were available, so this review makes no claims about how any particular one behaves.
Formula risk: spreadsheet applications may treat cells that begin with =, +, - or @ as formulas. If the data comes from untrusted sources, sanitize those values before sharing the file with spreadsheet users.
Useful to_csv parameters
| Parameter | What it does | Typical use |
| index | Writes the row index (default True) | index=False for default row numbers |
| index_label | Sets the header name for the index column | Keep a meaningful index clearly labeled |
| sep | Sets the field delimiter | "\t" for TSV, ";" where required |
| columns | Chooses which columns to write and their order | Export selected fields only |
| header | Writes column names, or replaces them with a list of aliases | header=False when appending rows |
| na_rep | Sets the text written for missing values | Match what the destination expects |
| float_format | Sets the format for floating-point values | Fixed decimals; reduces stored precision |
| encoding | Sets the text encoding | "utf-8-sig" for some spreadsheet apps |
| mode | Sets the file open mode | "a" to append to an existing file |
| compression | Compresses the output; inferred from extensions such as .gz or .zip | Large exports |
| date_format | Sets the format for datetime values | Consistent date strings |
Evidence gaps
This review is based on pandas' documented behavior and the general properties of CSV. No version-specific tests, file-size or speed comparisons, or checks against specific destinations were available. Before relying on behavior in a particular spreadsheet version, locale or assistive technology, confirm it with a small sample file. Parameter names have also changed between pandas releases; for example, line_terminator became lineterminator in version 1.5. Check the documentation for the version you have installed.