Logo

How to write a pandas DataFrame to CSV file?

Saving your data to a CSV file is one of the most common tasks in data analysis with Pandas. Once you’ve prepared or transformed your DataFrame, you can quickly export it to CSV for use in other applications or to share with others.

Below is a concise guide on how to accomplish this:

import pandas as pd # Sample DataFrame df = pd.DataFrame({ "Name": ["Alice", "Bob", "Charlie"], "Age": [25, 30, 35], "City": ["New York", "Chicago", "San Francisco"] }) # Writing DataFrame to a CSV file df.to_csv("output.csv", index=False)
  1. df.to_csv("output.csv"): Writes the DataFrame df to a CSV file named "output.csv" in the current working directory.
  2. index=False: Omits the row indices in the CSV file. By default, Pandas writes row indices as the first column, so this parameter removes them if you don’t need them.

Other Useful Parameters

  • sep=";": If you need to use a different delimiter (e.g., semicolon), you can specify it:
    df.to_csv("output_semicolon.csv", sep=";", index=False)
  • header=False: Omit the column names if needed.
  • columns=["Name", "City"]: If you only want to export certain columns.

Additional Tips

  • Check File Path: Make sure you have the correct path (absolute or relative) to avoid confusion about where the file is saved.
  • File Encoding: If you need a specific encoding (e.g., UTF-8, ISO-8859-1), pass encoding="utf-8" (or another as needed).

Recommended Next Steps

If you’re aiming to strengthen your Python skills—including data handling, best coding practices, and Python fundamentals—Grokking Python Fundamentals by DesignGurus.io is an excellent resource. This course will solidify your understanding of Python syntax, object-oriented features, file I/O operations, and more—paving the way for efficient data manipulation and analysis with Pandas.

Happy data wrangling!

CONTRIBUTOR
TechGrind