Sub topic 5
What a CSV round trip loses
This chapter assumes you can write a DataFrame with to_csv and know the basic dtypes (int, float, string, datetime, category). A round trip means writing a DataFrame to a file and reading it back. With CSV, the result often differs from the original.
Why CSV forgets types
A CSV file is plain text. It stores no dtypes, only characters separated by commas. When read_csv loads the file, it guesses each column's type from the text. Anything the text cannot express is lost.
Seeing the losses
This example writes four kinds of columns and reads them back.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3],
"zip": ["02134", "10001", "00501"],
"status": pd.Categorical(["new", "paid", "new"]),
"amount": [19.99, 5.5, None],
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"]),
})
df.to_csv("orders.csv", index=False)
back = pd.read_csv("orders.csv")
print(back.dtypes)
print(back["zip"].tolist())The output differs from the original in three ways:
zipcomes back asint64, and the values become2134,10001, and501. The leading zeros are gone.statuscomes back as plain text, notcategory.ordered_atcomes back as text, notdatetime64.
order_id and amount survive, because their values are unambiguous numbers.
Other common losses
| What you wrote | What you get back |
|---|---|
| Integer column with a missing value | `float64`, because `NaN` is a float |
| Empty string `""` and a missing value | Both read as `NaN` |
| Timezone-aware datetimes | Text with an offset, or `object` |
| Index written with `index=True` | An extra column named `Unnamed: 0` |
| Python objects such as lists or dicts | Their string form |
Floats can also change if you wrote them with float_format. Rounding to two decimals is permanent.
Restoring dtypes on read
You restore types by telling read_csv what the file contains. Use dtype for numbers, text, and categories. Use parse_dates for datetimes.
restored = pd.read_csv(
"orders.csv",
dtype={"zip": "string", "status": "category"},
parse_dates=["ordered_at"],
)
print(restored.dtypes)
print(restored["zip"].tolist())Now zip keeps 02134, status is category, and ordered_at is datetime64. The zip column uses the nullable string dtype. The original used object, so a strict comparison would still report a difference.
For integers with gaps, use the nullable integer type "Int64" (capital I). It stores missing values as <NA> and keeps the column integer.
ids = pd.DataFrame({"id": [1, 2, None]})
ids.to_csv("ids.csv", index=False)
print(pd.read_csv("ids.csv")["id"].dtype)
print(pd.read_csv("ids.csv", dtype={"id": "Int64"})["id"].dtype)The first line prints float64. The second prints Int64.
Distinguishing missing values from empty strings
If the difference between "no value" and an empty string matters, write an explicit marker and read it back with matching arguments.
df.to_csv("orders_na.csv", index=False, na_rep="NA")
pd.read_csv("orders_na.csv", keep_default_na=False, na_values=["NA"])With keep_default_na=False, only "NA" counts as missing. Empty strings stay as empty strings. Pick a marker that cannot appear in your real data.
Rules of thumb
- Treat the CSV as text and the
read_csvcall as the schema. Keep both in the same place in your code. - Read identifier columns, such as zip codes, phone numbers, and account numbers, as strings.
- If you need dtypes to survive without extra arguments, choose Parquet instead. A later chapter covers it.
Exercise
A CSV has a column account with values like "000417". After pd.read_csv("accounts.csv"), the values show as 417. Write the read_csv call that keeps the original values, and explain why the problem happened.
Show answer
Use pd.read_csv("accounts.csv", dtype={"account": "string"}). The file stores only text, and read_csv guessed that the column was numeric, so it converted "000417" to the integer 417 and dropped the leading zeros. Declaring the dtype stops the guess.