0

I'm writing a string from a dataframe. I want it to respect formatters, but I don't want headers in the string. How can I get both of these things: no header, yes formatting?

import pandas
df = pandas.DataFrame({'c': 1, 'd': 2.3}, index=[0], )
formats = {'c': '{: 10d}', 'd': '{: 2.5f}'}
formatters = {k: v.format for k, v in formats.items()}
df.to_string(formatters=formatters, index=False, header=True)

u'c        d\n        1  2.30000'


df.to_string(formatters=formatters, index=False, header=False)

'1  2.30000'

I believe the expected result is something like this?:

'         1  2.30000'
Hatshepsut
  • 5,962
  • 8
  • 44
  • 80
  • Headers meaning? You don't want the `1 ` to be printed along? – void Jun 28 '17 at 04:45
  • It seems to be only the leading empty characters that are removed. If filling with e.g. `0` it works, and also, the correct fractional part is retained. I also tried with multiple rows and it is only the first row that is affected. – JohanL Jun 28 '17 at 04:56

2 Answers2

1

[Disclaimer: I have never heard of DataFrame]

This just looks like a bug in DataFrame to me. Try reporting a bug to the developers.

As a workaround, it looks like you could just cut the first line off the string:

raw = df.to_string(formatters=formatters, index=False, header=True)
without_headers = '\n'.join(foo.splitlines()[1:])
robru
  • 2,313
  • 2
  • 29
  • 38
0

You could make a second DataFrame with everything formatted correctly

df2 = pd.DataFrame()
for col_name, col in df.iteritems():
    df2[col_name] = col.apply(lambda x: formats[col_name].format(x))

and then concatenate everything together

print(''.join(''.join(i[1:]) for i in df2.itertuples()))

'           1   2.30000'
Maarten Fabré
  • 6,938
  • 1
  • 17
  • 36