Pandas dataframe to string with separator

To convert a Pandas DataFrame to a string with a separator, you can use the to_string() method with the sep parameter. The to_string() method returns a string representation of the DataFrame, and the sep parameter allows you to specify the separator between columns.

Here is an example:

import pandas as pd

# Sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3],
                   'B': [4, 5, 6],
                   'C': [7, 8, 9]})

# Convert DataFrame to string with comma separator
df_string = df.to_string(sep=', ')

print(df_string)

This will output:

   A, B, C
0, 1, 4, 7
1, 2, 5, 8
2, 3, 6, 9

In this example, we first import the Pandas library. Then, we create a sample DataFrame with three columns (‘A’, ‘B’, and ‘C’). Finally, we use the to_string() method with sep=', ' to convert the DataFrame to a string with a comma and space separator.

You can change the separator to any character or combination of characters by modifying the sep parameter to fit your specific needs.

Leave a comment