Writing Data to Files
You've read data — now let's save it. Writing DataFrames to files is just as easy as reading them. Maybe even easier.
Saving to CSV
This is the most common one. One line and your data is saved:
import pandas as pd
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
df.to_csv('output.csv', index=False)
Notice the `index=False` parameter. Trust me, you'll want to use this most of the time. Without it, Pandas adds a column of row numbers to your file. That's usually just noise you don't need.
Saving to Excel
Need an Excel file? Same idea:
df.to_excel('output.xlsx', index=False)
Here is the thing — if you're sharing data with non-technical people, Excel files are usually the way to go. They can open it without worrying about Python or code.
Quick Tip
One thing that confused me at first was the `index` parameter. When you write to a file, `index=True` by default, which saves those 0, 1, 2 row labels. Almost always set `index=False` unless you specifically need those labels.
Try it Yourself →Key Takeaways
- Use `to_csv()` to save DataFrames as CSV files
- Use `to_excel()` to save as Excel files
- Always set `index=False` unless you need row labels
- Choose CSV for technical users, Excel for non-technical ones