diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 09c43822e11e4..c87c2dc534f36 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1254,7 +1254,7 @@ def to_string( col_space: int | list[int] | dict[Hashable, int] | None = None, header: bool | SequenceNotStr[str] = True, index: bool = True, - na_rep: str = "NaN", + na_rep: str = lib.no_default, formatters: fmt.FormattersType | None = None, float_format: fmt.FloatFormatType | None = None, sparsify: bool | None = None, diff --git a/pandas/core/series.py b/pandas/core/series.py index b02cee3c1fcf3..8746546611624 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1733,7 +1733,7 @@ def to_string( def to_string( self, buf: FilePath | WriteBuffer[str] | None = None, - na_rep: str = "NaN", + na_rep: str = lib.no_default, float_format: str | None = None, header: bool = True, index: bool = True, diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 1a7e4d7a80e13..7d23b111ddd67 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1223,17 +1223,30 @@ def _format_strings(self) -> list[str]: def _format(x): if self.na_rep is not None and is_scalar(x) and isna(x): - if x is None: - return "None" - elif x is NA: - return str(NA) - elif lib.is_float(x) and np.isinf(x): - # TODO(3.0): this will be unreachable when use_inf_as_na - # deprecation is enforced - return str(x) - elif x is NaT or isinstance(x, (np.datetime64, np.timedelta64)): - return "NaT" - return self.na_rep + if self.na_rep is lib.no_default: + if x is None: + return "None" + elif x is NA: + return str(NA) + elif lib.is_float(x) and np.isinf(x): + # TODO(3.0): this will be unreachable when use_inf_as_na + # deprecation is enforced + return str(x) + elif x is NaT or isinstance(x, (np.datetime64, np.timedelta64)): + return "NaT" + return "NaN" + else: + if x is None: + return "None" + elif x is NA: + return self.na_rep + elif lib.is_float(x) and np.isinf(x): + # TODO(3.0): this will be unreachable when use_inf_as_na + # deprecation is enforced + return str(x) + elif x is NaT or isinstance(x, (np.datetime64, np.timedelta64)): + return "NaT" + return self.na_rep elif isinstance(x, PandasObject): return str(x) elif isinstance(x, StringDtype):