Python3 dataframe mutiple separators

Viewed 101

I'm trying to take my df.to_csv which is sep="\t" and turn that tab into two spaces instead.

This question is similar but the solution isn't working: Pandas to_csv with multiple separators

\s+ won't work as python will complain that its not a single char separator.

This works as its a tab:

df2.to_csv('test.csv', index=False, sep='\t', quoting=csv.QUOTE_NONE, quotechar="", escapechar=None)

this throws TypeError: "delimiter" must be a 1-character string

df2.to_csv('test.csv', index=False, sep='\s+', quoting=csv.QUOTE_NONE, quotechar="", escapechar=None)
3 Answers

Let's look at using to_markdown instead of to_csv:

df = pd.DataFrame({'col1':'aaa bbb ccc'.split(), 'col2':[1, 10, 1000], 'col3': [True, False, True]})
df.to_markdown('a.txt', tablefmt='plain', index=False)
!type a.txt

File:

col1      col2  col3
aaa          1  True
bbb         10  False
ccc       1000  True

If you use numpy save text this will work:

np.savetxt(r"path\file.csv", your_df, delimiter='  ')

The answer on the linked question does seem to work without installing tabulate (trivial step really). Self-contained example:

import pandas as pd

# from @Scott Boston's example frame...
df = pd.DataFrame({'col1':'aaa bbb ccc'.split(), 'col2':[1, 10, 1000], 'col3': [True, False, True]})

# from @Scott Boston's answer...
# df.to_markdown('a.txt', tablefmt='plain', index=False)


# use a "weird char" for the sep value (well, weird to your data).  No file name...
temp = df.to_csv(sep='§')

temp = temp.replace('§', '  ')
with open('file.csv', 'w') as outfile:
    outfile.write(temp)

enter image description here

Related