Skip to content

Commit dd19a1d

Browse files
committed
BUG: format pd.NA
1 parent f30aeef commit dd19a1d

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

doc/source/whatsnew/v1.1.0.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -908,6 +908,8 @@ Missing
908908
- Clarified documentation on interpolate with method =akima. The ``der`` parameter must be scalar or None (:issue:`33426`)
909909
- :meth:`DataFrame.interpolate` uses the correct axis convention now. Previously interpolating along columns lead to interpolation along indices and vice versa. Furthermore interpolating with methods ``pad``, ``ffill``, ``bfill`` and ``backfill`` are identical to using these methods with :meth:`fillna` (:issue:`12918`, :issue:`29146`)
910910
- Bug in :meth:`DataFrame.interpolate` when called on a DataFrame with column names of string type was throwing a ValueError. The method is no independing of the type of column names (:issue:`33956`)
911+
- :class:`NA` will now always work when passed into a format string. Previously a ``ValueError`` was raised if any format parameters were supplied to the format string.
912+
For example ``"{:.1f}".format(pd.NA)`` would previously raise a ``ValueError``, but will now return the string ``"<NA>"`` (:issue:`xxxxx`)
911913

912914
MultiIndex
913915
^^^^^^^^^^

pandas/_libs/missing.pyx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,12 @@ class NAType(C_NAType):
349349
def __repr__(self) -> str:
350350
return "<NA>"
351351

352+
def __format__(self, format_spec) -> str:
353+
try:
354+
return self.__repr__().__format__(format_spec)
355+
except ValueError:
356+
return self.__repr__()
357+
352358
def __bool__(self):
353359
raise TypeError("boolean value of NA is ambiguous")
354360

pandas/tests/scalar/test_na_scalar.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,16 @@ def test_repr():
2222
assert str(NA) == "<NA>"
2323

2424

25+
def test_format():
26+
assert format(NA) == "<NA>"
27+
assert format(NA, ">10") == " <NA>"
28+
assert format(NA, "xxx") == "<NA>" # accept arbitrary format strings
29+
30+
assert "{}".format(NA) == "<NA>"
31+
assert "{:>10}".format(NA) == " <NA>"
32+
assert "{:xxx}".format(NA) == "<NA>" # accept arbitrary format strings
33+
34+
2535
def test_truthiness():
2636
msg = "boolean value of NA is ambiguous"
2737

0 commit comments

Comments
 (0)