Amelio Vazquez-Reina
Amelio Vazquez-Reina

Reputation: 96350

Printing to CSV file with automatic width

Is there any way in Pandas to write a DataFrame to a csv file where the column widths are automatically adjusted? (i.e. akin to what Pandas does when printing a DataFrame to the screen)

At the moment if I do

df.to_csv(string_buf, sep = ' ', Index=False)
print(string_buf.getvalue())

I get:

 column1 column2 column3
0 4 james matching68 -100
1 44 george foo -500
2 14 jason trinitron -400
3 1 tom trinitron -400
4 1 lukas esp -100

By the way, It's also strange that it prints the Index even though I explicitly disabled it.

Upvotes: 2

Views: 2116

Answers (1)

Phillip Cloud
Phillip Cloud

Reputation: 25672

At the risk of being called Captain Obvious™, why not just write the result of to_string() to a file?

with open('csv.csv', 'w') as f:
    f.write(df.to_string())

If you don't want to write the index you'll probably need to use numpy:

df = DataFrame(randn(10, 3), columns=list('abc'))
values = df.values
columns = df.columns.values

with open('csv.csv', 'w') as f:
    savetxt(f, columns[newaxis], fmt='%10s')
    savetxt(f, values, fmt='%10.4f')

cat csv.csv:

      a          b          c
-0.8023    -0.6464    -0.2102
-1.4442    -0.5965     1.7326
 1.5028     1.7246    -0.4788
-1.6442    -0.3962     0.1391
 1.2404     1.1226    -0.3639
-0.6567     1.3464     0.2167
 0.4928     0.2204    -0.8549
-1.0625    -0.6588    -1.0551
-0.9175    -0.5855    -0.4151

Upvotes: 2

Related Questions