Sub topic 5
What a CSV round trip loses
This chapter assumes you can write a DataFrame with to_csv and know the options from the previous chapters (index, sep, na_rep, float_format). It also assumes you know pandas dtypes such as int64, float64, datetime64, category, and the nullable Int64 and string types.
A round trip means writing a DataFrame to a file and reading it back. With CSV, the result often looks the same when you print it, but its dtypes and some values are different. This chapter explains why, lists what changes, and shows how to restore the original types.
Why CSV loses information
A CSV file is plain text. It holds rows of characters separated by a delimiter. It does not record whether a column was an integer, a date, a category, or a string that happens to contain digits.
When read_csv loads the file, it infers each column's type from the text:
- If every value looks like an integer, the column becomes
int64. - If values look like decimals, or some are empty in a numeric column, it becomes
float64. - If values are
TrueandFalse, it becomesbool. - Anything else becomes strings (
object, orstrin pandas 3).
Dates are never detected unless you ask for them. The writer's knowledge of the original dtypes is not in the file.
See the loss in one example
The DataFrame below has a zip code that starts with zero, a country code of "NA" (Namibia), a categorical column, a nullable integer column, a float with a missing value, and a datetime column.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3],
"zip_code": ["02134", "10001", "94105"],
"country": ["US", "NA", "DE"],
"status": pd.Categorical(["paid", "open", "paid"]),
"quantity": pd.array([2, None, 5], dtype="Int64"),
"amount": [19.99, 5.5, None],
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"]),
})
df.to_csv("orders_rt.csv", index=False)
back = pd.read_csv("orders_rt.csv")
print(df.dtypes)
print()
print(back.dtypes)
print()
print(back)Compare the two dtype listings. In back you will see these changes:
zip_codeisint64, and the value02134is now2134. The leading zero is gone.countryhas a missing value where"NA"used to be.statusis a plain string column, notcategory.quantityisfloat64, with2.0,NaN, and5.0.ordered_atis a string column, notdatetime64.
Only order_id and amount came back as they were.
Common losses and their fixes
| What you wrote | What `read_csv` returns by default | Fix when reading |
|---|---|---|
| `datetime64` column | Strings | `parse_dates=["col"]` |
| Timezone-aware datetimes | Strings, or a fixed offset instead of the named zone | Parse with `utc=True`, then `tz_convert` |
| `category` | Strings | `dtype={"col": "category"}` |
| Strings that look like numbers (zip codes, IDs) | Integers, with leading zeros dropped | `dtype={"col": "string"}` |
| Nullable `Int64` with missing values | `float64` | `dtype={"col": "Int64"}` |
| `bool` with missing values | Strings (`object`) | `dtype={"col": "boolean"}` |
| Strings such as `"NA"`, `"null"`, `"N/A"` | Missing values | `keep_default_na=False` and your own `na_values` |
| Empty string and `None` | Both become `NaN` | Write a distinct `na_rep`, and read it back explicitly |
| Index (written with `index=True`) | An extra `Unnamed: 0` column | `index_col=0`, or write with `index=False` |
| Floats written with `float_format` | The rounded values | None. The digits are gone. |
The last row cannot be repaired by any read argument. Formatting options such as float_format="%.2f" change the data in the file. They are fine for a report, but they make the file unsuitable as a lossless copy.
Restoring dtypes when you read
You restore types by telling read_csv what you know. Here is the repaired read for the example above.
restored = pd.read_csv(
"orders_rt.csv",
dtype={
"zip_code": "string",
"country": "string",
"status": "category",
"quantity": "Int64",
},
parse_dates=["ordered_at"],
keep_default_na=False,
na_values=[""],
)
print(restored.dtypes)
print(restored)Three arguments do the work:
dtypetakes a dict from column name to dtype. Using"string"forzip_codemeans the parser never tries to convert it to a number, so02134stays intact.parse_datesconverts the listed columns todatetime64.keep_default_na=Falsewithna_values=[""]turns off the built-in list of missing-value strings. That list includes"NA","N/A","NULL","NaN", and"n/a". Only an empty field counts as missing, so the country"NA"survives.
Missing values are the trickiest part
A written empty field is ambiguous. None, NaN, pd.NA, and an empty string "" all appear as nothing between two delimiters. Reading cannot tell them apart.
If the difference matters, give missing values their own marker on write and read it back explicitly:
people = pd.DataFrame({
"name": ["Ana", "", None],
"note": ["ok", "NA", "ok"],
})
people.to_csv("people.csv", index=False, na_rep="__MISSING__")
people_back = pd.read_csv(
"people.csv",
keep_default_na=False,
na_values=["__MISSING__"],
)
print(people_back)Here None returns as NaN, the empty string stays "", and the note "NA" stays text. The cost is that the marker is now part of your file format. Anyone else who reads the file must know about it, so document it. Choose a marker that cannot occur in real data.
Timezones
to_csv writes timezone-aware datetimes with a numeric UTC offset, such as +01:00. The zone name (for example Europe/Berlin) is not stored.
ts = pd.DataFrame({
"t": pd.to_datetime(["2026-03-01 09:00", "2026-03-01 10:30"]).tz_localize("Europe/Berlin")
})
ts.to_csv("ts.csv", index=False)
with open("ts.csv") as f:
print(f.read())
back_ts = pd.read_csv("ts.csv")
back_ts["t"] = pd.to_datetime(back_ts["t"], utc=True).dt.tz_convert("Europe/Berlin")
print(back_ts.dtypes)Parsing with utc=True gives every value the same zone, so mixed offsets cannot break the column. A column that spans a daylight saving change has two different offsets. Without utc=True, such a column can come back as strings. After the UTC conversion you apply the zone you know the data belongs to with tz_convert. The file does not tell you that zone. You must keep that knowledge in your code, your documentation, or the file name.
The index
By default to_csv writes the index as the first column. Reading that file gives you an extra column named Unnamed: 0, because the index had no header text. You have two clean options:
df.to_csv("with_index.csv") # index written as first column
a = pd.read_csv("with_index.csv", index_col=0) # index restored
df.to_csv("no_index.csv", index=False)
b = pd.read_csv("no_index.csv") # fresh RangeIndexUse index=False when the index is just row numbers. Use index=True with index_col when the index carries meaning, such as an order ID or a timestamp. A MultiIndex needs index_col=[0, 1], and the level names come from the header.
Floating-point precision
By default to_csv writes each float with enough digits to identify the exact value. Reading gives back the same number in almost every case. The default float converter in read_csv is fast rather than exact, and in rare cases the last bit can differ. If you need bit-for-bit equality, pass float_precision="round_trip":
pd.read_csv("orders_rt.csv", float_precision="round_trip")Do not use float_format on a file you want to treat as a lossless copy. Rounding happens at write time and you cannot undo it.
Keep the schema in one place
If you write and read the same file in several scripts, the dtype arguments tend to drift apart. Define them once and import them from both sides:
ORDER_READ_ARGS = {
"dtype": {
"zip_code": "string",
"country": "string",
"status": "category",
"quantity": "Int64",
},
"parse_dates": ["ordered_at"],
"keep_default_na": False,
"na_values": [""],
}
restored = pd.read_csv("orders_rt.csv", **ORDER_READ_ARGS)This works as a lightweight schema. When a new column needs special handling, you change one place.
Checking your result
After restoring, compare dtypes and values against the original, as covered in the chapter on verifying files. Expect some differences even then. The zip_code column in the original DataFrame has object dtype, while the restored one has string, so a strict comparison fails unless you align the two first.
Exercise
A file customers.csv has a column customer_id with values such as 00417, a column signup_date with ISO dates, and a column region where some rows contain the text NA meaning North America. You load it with pd.read_csv("customers.csv"). Name three problems you will see, and write a read_csv call that avoids them.
Show answer
The three problems are: customer_id becomes an integer and loses its leading zeros (417), signup_date is loaded as strings, and the NA regions become missing values. A call that avoids them:
pd.readcsv(
"customers.csv",
dtype={"customerid": "string", "region": "string"},
parsedates=["signupdate"],
keepdefaultna=False,
navalues=[""],
)
dtype keeps the IDs as text, `parsedates gives a datetime column, and keepdefaultna=False with na_values=[""] treats only empty fields as missing, so NA` stays as text.