2

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?

terencezl
  • 69
  • 1
  • 8

2 Answers2

3

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.

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
  • Awesome! I knew there should be a most straightforward way. But why doesn't this method accept a simple string for `float_format`, but it has to be a function? Just like to_csv()? – terencezl Nov 08 '14 at 05:21
  • I don't know. That confused me, too. Having the same argument name in similar functions behave differently is an unfortunate API design choice. – Warren Weckesser Nov 08 '14 at 07:07
0

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('^', '')
John Zwinck
  • 239,568
  • 38
  • 324
  • 436