Skip to content

ENH: Add argument to apply formatters in DataFrame.to_string to the index #47584

Open
@ntjess

Description

@ntjess

Pandas version checks

  • I have checked that the issue still exists on the latest versions of the docs on main here

Location of the documentation

https://pandas.pydata.org/docs/dev/reference/api/pandas.DataFrame.to_string.html?highlight=formatters

Documentation problem

The current to_string documentation for formatters indicates formatting can be applied to columns, but it is unclear whether anything can be set for the index as well. Deep within format.py, it appears adding an __index__ key to formatters will handle this well. I tested with the code below which seemed to work:

import pandas as pd
fmt = "{:.4f}".format
fmt_dict = dict(__index__=fmt)
print(pd.DataFrame([[1,2,3]]).to_string(formatters=fmt_dict))

Is this feature meant to be public? If so, I would recommend exposing it in the formatters parameter description. Thanks!

Suggested fix for documentation

New formatters description resembling the following. Added sentence is italicized:

Formatter functions to apply to columns’ elements by position or name. The result of each function must be a unicode string. List/tuple must be of length equal to the number of columns. If a dict-like formatter is specified, the dataframe's index can be formatted with an __index__ key.


Alternatively, the MWE in this issue (or something similar) can be added to the Examples section.

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementNeeds DiscussionRequires discussion from core team before further actionOutput-Formatting__repr__ of pandas objects, to_string

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions