close

How to set a custom separator in pandas to_csv()?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to set a custom separator in pandas to_csv() in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to set a custom separator in pandas to_csv()?

  1. How to set a custom separator in pandas to_csv()?

    This is an old post, but I always seem to land here when googling how to export Dataframe to csv.

  2. set a custom separator in pandas to_csv()

    This is an old post, but I always seem to land here when googling how to export Dataframe to csv.

Method 1

This is an old post, but I always seem to land here when googling how to export Dataframe to csv.

Although you can’t do it directly with Pandas, you can do it with Numpy.

Since Pandas requires Numpy, you are not increasing your package size.

To do what you want, you can simply do:

import numpy as np
np.savetxt('out.csv', my_df, delimiter=':::')

Numpy offers a greater api to save csv files. You can even specify different separators using:

import numpy as np
np.savetxt('out.csv', my_df, fmt=['%.2f:::', '%f', '%s'])

Method 2

Obviously Pandas seems not to allow this behavior.

However, if you absolutely want “:::”. Why not exporting the dataframe with an uncommon character such as “|” and then open back the file and replace “|” by “:::”.

That’s the only solution I imagine to perform your desired result.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read