Writing Data Out
After cleaning and analysing, you usually need to hand the result to someone or something else: a CSV for a colleague, JSON for a web app, a Python dictionary for your own code. Every read_* function in pandas has a matching to_* method.
| Format | Write | Read back |
|---|---|---|
| CSV | df.to_csv(path) |
pd.read_csv(path) |
| JSON | df.to_json(path) |
pd.read_json(path) |
| Excel | df.to_excel(path) (needs openpyxl) |
pd.read_excel(path) |
| Parquet | df.to_parquet(path) (needs pyarrow) |
pd.read_parquet(path) |
| SQL database | df.to_sql(name, connection) |
pd.read_sql(query, connection) |
| Python objects | df.to_dict(), df.to_numpy() |
pd.DataFrame(...) |
In a real script you pass a file name:
summary.to_csv("summary.csv", index=False)
summary.to_json("summary.json", orient="records", indent=2)
summary.to_excel("summary.xlsx", sheet_name="Summary", index=False)The playgrounds can't write files, but to_csv() and to_json() return a string when you don't give a path, so we can see exactly what would be written.
to_csv()
import pandas as pd
menu = pd.DataFrame({
"dish": ["Ramen", "Pho", "Laksa"],
"price": [11.5, 10.0, 12.25],
"spicy": [False, False, True],
})
print(menu.to_csv())
print(menu.to_csv(index=False)),dish,price,spicy
0,Ramen,11.5,False
1,Pho,10.0,False
2,Laksa,12.25,True
dish,price,spicy
Ramen,11.5,False
Pho,10.0,False
Laksa,12.25,True
By default the index is written as an unnamed first column. When the index is just 0, 1, 2…, pass index=False; otherwise reading the file back gives you an extra Unnamed: 0 column.
Formatting options
import numpy as np
import pandas as pd
menu = pd.DataFrame({
"dish": ["Ramen", "Pho", "Laksa"],
"price": [11.5, 10.0, np.nan],
})
print(menu.to_csv(index=False, sep=";", decimal=",", na_rep="n/a",
float_format="%.2f"))dish;price
Ramen;11,50
Pho;10,00
Laksa;n/a
| Option | Effect |
|---|---|
index=False |
don't write the index |
sep=";" |
column separator |
columns=[...] |
write only these columns |
na_rep="n/a" |
text for missing values |
float_format="%.2f" |
number format |
decimal="," |
decimal mark |
header=False |
omit column names |
A round trip
Writing and reading back should give the same data. Testing this is a good habit, and equals() compares two frames exactly:
import io
import pandas as pd
original = pd.DataFrame({
"day": pd.to_datetime(["2024-04-01", "2024-04-02"]),
"visitors": [310, 287],
})
text = original.to_csv(index=False)
restored = pd.read_csv(io.StringIO(text), parse_dates=["day"])
print(restored.dtypes)
print("identical:", original.equals(restored))day datetime64[ns]
visitors int64
dtype: object
identical: True
Without parse_dates, the dates would come back as text and equals would be False. CSV stores everything as text, so types must be restored when reading. That's one reason binary formats like Parquet are popular for large data.
to_json()
import pandas as pd
menu = pd.DataFrame({
"dish": ["Ramen", "Pho"],
"price": [11.5, 10.0],
})
print(menu.to_json(orient="records"))
print(menu.to_json(orient="records", indent=2))
print(menu.set_index("dish").to_json(orient="index"))[{"dish":"Ramen","price":11.5},{"dish":"Pho","price":10.0}]
[
{
"dish":"Ramen",
"price":11.5
},
{
"dish":"Pho",
"price":10.0
}
]
{"Ramen":{"price":11.5},"Pho":{"price":10.0}}
orient works just like in read_json. For web APIs, "records" (a list of objects) is the most common.
Python objects
import pandas as pd
menu = pd.DataFrame({
"dish": ["Ramen", "Pho"],
"price": [11.5, 10.0],
})
print(menu.to_dict())
print(menu.to_dict(orient="records"))
print(menu.set_index("dish")["price"].to_dict())
print(menu.to_numpy()){'dish': {0: 'Ramen', 1: 'Pho'}, 'price': {0: 11.5, 1: 10.0}}
[{'dish': 'Ramen', 'price': 11.5}, {'dish': 'Pho', 'price': 10.0}]
{'Ramen': 11.5, 'Pho': 10.0}
[['Ramen' 11.5]
['Pho' 10.0]]
to_dict(orient="records") gives a list of row dictionaries, ready for json.dumps or a template engine. A Series' to_dict() gives a simple label → value lookup.
Tip:
df.to_string()returns the printed table as text, anddf.to_html()returns an HTML<table>, handy for emails and quick reports.
Test yourself
Why pass index=False to to_csv for a frame with the default 0, 1, 2… index?
- To make the file smaller and avoid an extra unnamed column when reading back
- Because the index can't be written
- To sort the rows
- It is required
What does df.to_csv() return when you don't pass a path?
- None
- The CSV text as a string
- A file object
- An error
Which call produces a list of dictionaries, one per row?
- df.to_dict()
- df.to_dict(orient="records")
- df.to_list()
- df.values