Skip to content

DOC: .to_string float_format behavior inconsistent with documentation and different for extension types #53675

@zmoon

Description

@zmoon

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/pandas-docs/stable/reference/api/pandas.DataFrame.to_string.html

Documentation problem

DataFrame.to_string docstring says float_format should be "one-parameter function, optional, default None", but passing a format string (e.g. '%.3e') works too, like in .to_csv, for NumPy float type columns/series.

However, unlike .to_csv, .to_string with float_format string fails with TypeError: 'str' object is not callable for float extension type columns/series.

s = pd.Series([1.1, 2.2, 3.3])

# works
s.to_csv(float_format="%.3e")
s.convert_dtypes().to_csv(float_format="%.3e")
s.to_string(float_format="%.3e")

# fails
s.convert_dtypes().to_string(float_format="%.3e")

xref: #9448 pandas-dev/pandas-stubs#730

Suggested fix for documentation

It would be nice for the documentation to reflect that a format string can be used, but probably the issue with extension types should be fixed first.

Note also that FloatFormatType, used in the internal typing of DataFrame.to_string,

float_format: fmt.FloatFormatType | None = ...,

does include str as an option.

FloatFormatType = Union[str, Callable, "EngFormatter"]

Metadata

Metadata

Assignees

Labels

BugDocsExtensionArrayExtending pandas with custom dtypes or arrays.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions