Skip to content

GH730 allow str for float format to string #1200

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pandas-stubs/_typing.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -626,7 +626,7 @@ CompressionOptions: TypeAlias = (
FormattersType: TypeAlias = (
list[Callable] | tuple[Callable, ...] | Mapping[str | int, Callable]
)
FloatFormatType: TypeAlias = str | Callable | EngFormatter
FloatFormatType: TypeAlias = str | Callable[[float], str] | EngFormatter
# converters
ConvertersArg: TypeAlias = dict[Hashable, Callable[[Dtype], Dtype]]

Expand Down
9 changes: 6 additions & 3 deletions pandas-stubs/core/frame.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ from typing import (
overload,
)

from _typing import TimeZones
from _typing import (
FloatFormatType,
TimeZones,
)
from matplotlib.axes import Axes as PlotAxes
import numpy as np
from pandas import (
Expand Down Expand Up @@ -2311,7 +2314,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack):
index: _bool = ...,
na_rep: _str = ...,
formatters: FormattersType | None = ...,
float_format: Callable[[float], str] | None = ...,
float_format: FloatFormatType | None = ...,
sparsify: _bool | None = ...,
index_names: _bool = ...,
justify: _str | None = ...,
Expand All @@ -2334,7 +2337,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack):
index: _bool = ...,
na_rep: _str = ...,
formatters: FormattersType | None = ...,
float_format: Callable[[float], str] | None = ...,
float_format: FloatFormatType | None = ...,
sparsify: _bool | None = ...,
index_names: _bool = ...,
justify: _str | None = ...,
Expand Down
5 changes: 3 additions & 2 deletions pandas-stubs/core/series.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ from typing import (
)

from _typing import (
FloatFormatType,
Label,
ReplaceValue,
TimeZones,
Expand Down Expand Up @@ -530,7 +531,7 @@ class Series(IndexOpsMixin[S1], NDFrame):
self,
buf: FilePath | WriteBuffer[str],
na_rep: _str = ...,
float_format: Callable[[float], str] = ...,
float_format: FloatFormatType = ...,
header: _bool = ...,
index: _bool = ...,
length: _bool = ...,
Expand All @@ -544,7 +545,7 @@ class Series(IndexOpsMixin[S1], NDFrame):
self,
buf: None = ...,
na_rep: _str = ...,
float_format: Callable[[float], str] = ...,
float_format: FloatFormatType = ...,
header: _bool = ...,
index: _bool = ...,
length: _bool = ...,
Expand Down
22 changes: 22 additions & 0 deletions tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
pytest_warns_bounded,
)

from pandas.io.formats.format import EngFormatter
from pandas.io.formats.style import Styler
from pandas.io.parsers import TextFileReader

Expand Down Expand Up @@ -1698,6 +1699,27 @@ def test_types_to_string() -> None:
df.to_string(col_space={"col1": 1, "col2": 3})


def test_dataframe_to_string_float_fmt() -> None:
"""Test the different argument types for float_format."""
df = pd.DataFrame(
{"values": [2.304, 1.1, 3487392, 13.4732894237, 14.3, 18.0, 17.434, 19.3]}
)
check(assert_type(df.to_string(), str), str)

def _formatter(x) -> str:
return f"{x:.2f}"

check(assert_type(df.to_string(float_format=_formatter), str), str)
check(
assert_type(
df.to_string(float_format=EngFormatter(accuracy=2, use_eng_prefix=False)),
str,
),
str,
)
check(assert_type(df.to_string(float_format="%.2f"), str), str)


def test_types_to_html() -> None:
df = pd.DataFrame(
data={
Expand Down
23 changes: 23 additions & 0 deletions tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@
)
from tests.extension.decimal.array import DecimalDtype

from pandas.io.formats.format import EngFormatter

if TYPE_CHECKING:
from pandas.core.series import (
OffsetSeries,
Expand Down Expand Up @@ -2932,6 +2934,27 @@ def test_to_string() -> None:
)


def test_series_to_string_float_fmt() -> None:
"""Test the different argument types for float_format."""
sr = pd.Series(
[2.304, 1.1, 3487392, 13.4732894237, 14.3, 18.0, 17.434, 19.3], name="values"
)
check(assert_type(sr.to_string(), str), str)

def _formatter(x) -> str:
return f"{x:.2f}"

check(assert_type(sr.to_string(float_format=_formatter), str), str)
check(
assert_type(
sr.to_string(float_format=EngFormatter(accuracy=2, use_eng_prefix=False)),
str,
),
str,
)
check(assert_type(sr.to_string(float_format="%.2f"), str), str)


def test_types_mask() -> None:
s = pd.Series([1, 2, 3, 4, 5])

Expand Down