Skip to content

Commit 594dc2a

Browse files
authored
BUG: pd.NA.__format__ fails with format_specs (#34740)
1 parent 18f9460 commit 594dc2a

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -931,6 +931,7 @@ Missing
931931
- Clarified documentation on interpolate with method =akima. The ``der`` parameter must be scalar or None (:issue:`33426`)
932932
- :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`)
933933
- 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`)
934+
- passing :class:`NA` will into a format string using format specs will now work. For example ``"{:.1f}".format(pd.NA)`` would previously raise a ``ValueError``, but will now return the string ``"<NA>"`` (:issue:`34740`)
934935

935936
MultiIndex
936937
^^^^^^^^^^

pandas/_libs/missing.pyx

+6
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

+11
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,17 @@ def test_repr():
2222
assert str(NA) == "<NA>"
2323

2424

25+
def test_format():
26+
# GH-34740
27+
assert format(NA) == "<NA>"
28+
assert format(NA, ">10") == " <NA>"
29+
assert format(NA, "xxx") == "<NA>" # NA is flexible, accept any format spec
30+
31+
assert "{}".format(NA) == "<NA>"
32+
assert "{:>10}".format(NA) == " <NA>"
33+
assert "{:xxx}".format(NA) == "<NA>"
34+
35+
2536
def test_truthiness():
2637
msg = "boolean value of NA is ambiguous"
2738

0 commit comments

Comments
 (0)