Skip to content

Commit 977bcf8

Browse files
JustinZhengBCjreback
authored andcommitted
BUG-25061 fix printing indices with NaNs (#25202)
1 parent 04df22f commit 977bcf8

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

doc/source/whatsnew/v0.24.2.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ Bug Fixes
5252
**I/O**
5353

5454
- Bug in reading a HDF5 table-format ``DataFrame`` created in Python 2, in Python 3 (:issue:`24925`)
55-
-
55+
- Bug where float indexes could have misaligned values when printing (:issue:`25061`)
5656
-
5757

5858
**Categorical**

pandas/io/formats/format.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -1060,19 +1060,26 @@ def get_result_as_array(self):
10601060
def format_values_with(float_format):
10611061
formatter = self._value_formatter(float_format, threshold)
10621062

1063+
# default formatter leaves a space to the left when formatting
1064+
# floats, must be consistent for left-justifying NaNs (GH #25061)
1065+
if self.justify == 'left':
1066+
na_rep = ' ' + self.na_rep
1067+
else:
1068+
na_rep = self.na_rep
1069+
10631070
# separate the wheat from the chaff
10641071
values = self.values
10651072
mask = isna(values)
10661073
if hasattr(values, 'to_dense'): # sparse numpy ndarray
10671074
values = values.to_dense()
10681075
values = np.array(values, dtype='object')
1069-
values[mask] = self.na_rep
1076+
values[mask] = na_rep
10701077
imask = (~mask).ravel()
10711078
values.flat[imask] = np.array([formatter(val)
10721079
for val in values.ravel()[imask]])
10731080

10741081
if self.fixed_width:
1075-
return _trim_zeros(values, self.na_rep)
1082+
return _trim_zeros(values, na_rep)
10761083

10771084
return values
10781085

pandas/tests/series/test_repr.py

+8
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,14 @@ def test_latex_repr(self):
198198

199199
assert s._repr_latex_() is None
200200

201+
def test_index_repr_in_frame_with_nan(self):
202+
# see gh-25061
203+
i = Index([1, np.nan])
204+
s = Series([1, 2], index=i)
205+
exp = """1.0 1\nNaN 2\ndtype: int64"""
206+
207+
assert repr(s) == exp
208+
201209

202210
class TestCategoricalRepr(object):
203211

0 commit comments

Comments
 (0)