Pandas to_csv() - Convert DataFrame to CSV With Examples

Pandas DataFrame to_csv() function converts DataFrame into CSV data. We can pass a file object to write the CSV data into a file. Otherwise, the CSV data is returned in the string format.

Pandas DataFrame to_csv() Syntax

The syntax of DataFrame to_csv() function is:

Some of the important parameters are:

  • path_or_buf: the file object to write the CSV data. If this argument is not provided, the CSV data is returned as a string.
  • sep: the delimiter for the CSV data. It should be a string of length 1, the default is a comma.
  • na_rep: string representing null or missing values, default is empty string.
  • columns: a sequence to specify the columns to include in the CSV output.
  • header: the allowed values are boolean or a list of string, default is True. If False, the column names are not written in the output. If a list of string, it’s used to write the column names. The length of the list of string should be the same as the number of columns being written in the CSV file.
  • index: if True, index is included in the CSV data. If False, the index value is not written in the CSV output.
  • index_label: used to specify the column name for index.

Pandas DataFrame to CSV Examples

Let’s look at some common examples of using to_csv() function to convert DataFrame to CSV data.

1. Converting DataFrame to CSV String

Output:

2. Specifying Delimiter for the CSV Output

Output:

If the specified delimiter length is not 1, TypeError: “delimiter” must be a 1-character string is raised.

3. Selecting only few columns for CSV Output

Output:

Notice that the index is not considered to be a valid column.

Output:

5. Setting Custom Column Names in the CSV

Output:

Again the index is not considered as the column of DataFrame object.

6. Skipping Index Column in CSV Output

Output:

7. Setting Index Column Name in the CSV

Output:

8. Converting DataFrame to CSV File

We are using with statement to open the file, it takes care of closing the file when the with statement block execution is finished.

This code snippet will create a CSV file with the following data.

9. Null, NA, or Missing Data Representation in the CSV Output

Output:

References

By admin

Leave a Reply

%d bloggers like this: