Hatshepsut
Hatshepsut

Reputation: 6652

Using formatters to make string from dataframe

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'

Upvotes: 0

Views: 3536

Answers (2)

Maarten Fabré
Maarten Fabré

Reputation: 7058

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'

Upvotes: 0

robru
robru

Reputation: 2383

[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:])

Upvotes: 1

Related Questions