Writing Data in Pandas

Last Updated: 28th August 2025


What you'll learn

  • Save DataFrames into different formats: CSV, Excel, JSON, SQL
  • Important parameters: index, header, sep, na_rep, columns

Hinglish Tip 🗣: Data ko load karna easy hai, par sahi format me save/export karna aur bhi important hai. Jaise analysis ke baad CSV bhejna ho ya Excel report banana ho.


Let data is like this

import pandas as pd

df = pd.DataFrame({
    "ID": [1, 2, 3],
    "Name": ["A", "B", "C"],
    "Marks": [85, 90, None]
})

📤 CSV — to_csv()

# Basic save
df.to_csv("output.csv")

import pandas as pd

# With useful options
df.to_csv(
    "output.csv",
    index=False,            # Don't save row index
    sep=";",                # Change separator
    na_rep="NA",            # Missing values as "NA"
    columns=["ID", "Name"], # Save only specific columns
    compression="gzip"      # Compress file
)

🗂 Excel — to_excel()

# Save as Excel file
df.to_excel(
    "output.xlsx",
    index=False,
    sheet_name="Results",
    na_rep="NA"
)

🗂 JSON — to_json()

# Save as JSON records (easy to share with APIs)
df.to_json("output.json", orient="records")

# Save as line-delimited JSON (newline per record)
df.to_json("output_lines.json", orient="records", lines=True)

🗂 SQL — to_sql()

import sqlite3
import pandas as pd
import sqlite3

conn = sqlite3.connect("mydb.sqlite")

# Save dataframe to SQL table
df.to_sql(
    "students",
    conn,
    if_exists="replace",   # "replace" old table, or use "append"
    index=False,
    method="multi"         # Use for bulk insert
)

conn.close()