terencezl
terencezl

Reputation: 69

np.savetxt style nicely tabulated output for pandas DataFrame.to_csv

I pulled off some hair but still cannot obtain a nicely tabulated output.

In a word, I would like the file saved by the .to_csv() method to look like this:

               K0         V0     dK_dT         a             b
value  237.496942  82.845746 -0.037012  0.000006  1.359708e-08
std      2.094088   0.012948  0.004415  0.000001  1.550236e-09

But with what I can do, print result.to_csv(float_format='%10.2g', sep=' ') gives me:

 K0 V0 dK_dT a b
value "   2.4e+02" "        83" "    -0.037" "   5.8e-06" "   1.4e-08"
std "       2.1" "     0.013" "    0.0044" "     1e-06" "   1.6e-09"
  1. the header does not automatically align.
  2. the quotes disrupt the equal width flow.

I tried setting quoting to some csv.QUOTE_MINIMAL which are essentially ints but with no luck. As far as I know, NumPy can easily do this with savetxt(format='%10.2g').

Anything I missed?

Upvotes: 2

Views: 2445

Answers (2)

Warren Weckesser
Warren Weckesser

Reputation: 114841

Instead of to_csv(), you could use to_string(). For example,

In [80]: df
Out[80]: 
            A         B             C
a  123.456789  0.702380  7.071752e-08
b    1.230000  0.323674  6.075386e-08
c    0.012300  0.621974  7.918532e-08
d    0.000000  0.818291  5.480469e-08
e   -9.876543  0.117978  9.831873e-08

In [81]: txt = df.to_string()

In [82]: print txt
            A         B             C
a  123.456789  0.702380  7.071752e-08
b    1.230000  0.323674  6.075386e-08
c    0.012300  0.621974  7.918532e-08
d    0.000000  0.818291  5.480469e-08
e   -9.876543  0.117978  9.831873e-08

You can then write txt to a file.

Upvotes: 3

John Zwinck
John Zwinck

Reputation: 249223

Here's a silly trick: use ASCII BEL (bell) as your quote character. At least on my system this prints no quotes at all:

result.to_csv(float_format='%10.2g', sep=' ', index=False, quotechar='\a')

Or use a dummy character and replace it at the end:

ss = result.to_csv(float_format='%10.2g', sep=' ', index=False, quotechar='^')
print ss.replace('^', '')

Upvotes: 0

Related Questions