Sub topic 2
What a CSV Round Trip Loses
Assume you know basic Python, pandas DataFrames, and common dtypes such as integers, floats, strings, and datetimes.
What a CSV round trip loses
CSV stores a table as text. It does not store pandas metadata such as a column's dtype, index type, or missing-value type. A round trip means writing a DataFrame and reading it back.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3],
"customer": ["Ana", "Ben", None],
"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)
restored = pd.read_csv(
"orders.csv",
parse_dates=["ordered_at"],
dtype={"order_id": "int64"},
)Without parse_dates, ordered_at usually returns as strings. Missing values may become NaN, and integer columns with missing values may become floating-point columns. CSV also cannot preserve categories, timedeltas, indexes, or custom Python objects without extra conventions.
Saving a DataFrame to Excel
to_excel writes a workbook that spreadsheet users can open. Excel output needs an engine, commonly openpyxl.
df.to_excel("orders.xlsx", sheet_name="orders", index=False)The index=False argument prevents pandas from adding the DataFrame index as an extra column.
Writing several sheets to one workbook
Use ExcelWriter as a context manager when writing multiple sheets. The context manager closes and saves the workbook safely.
summary = df.groupby("customer", dropna=True)["amount"].sum().to_frame()
with pd.ExcelWriter("report.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="orders", index=False, freeze_panes=(1, 0))
summary.to_excel(writer, sheet_name="summary")Excel limits, engines, and light formatting
Excel has a worksheet limit of 1,048,576 rows and 16,384 columns. It is therefore a poor choice for very large results. Install the engine you need, such as openpyxl for .xlsx files. Options such as freeze_panes, column widths, and number formats provide useful light formatting, but pandas is not a full spreadsheet-design tool.
Exercise
Why can a CSV round trip change an integer column into a float column?
Show answer
A CSV stores only text. When an integer column contains a missing value, pandas commonly uses NaN, which requires a floating-point representation unless a nullable integer dtype is specified.