Skip to content

Commit de31cbe

Browse files
committed
BUG: don't truncate small FP numbers to zero in DataFrame formatting close #1911
1 parent f1c51ce commit de31cbe

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

RELEASE.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@ pandas 0.9.0
178178
- Fix negative integer indexing regression in .ix from 0.7.x (#1888)
179179
- Fix error while retrieving timezone and utc offset from subclasses of
180180
datetime.tzinfo without .zone and ._utcoffset attributes (#1922)
181+
- Fix DataFrame formatting of small, non-zero FP numbers (#1911)
181182

182183
pandas 0.8.1
183184
============

pandas/core/format.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -667,12 +667,19 @@ def get_result(self):
667667

668668
too_long = maxlen > self.digits + 5
669669

670+
abs_vals = np.abs(self.values)
671+
670672
# this is pretty arbitrary for now
671-
has_large_values = (np.abs(self.values) > 1e8).any()
673+
has_large_values = (abs_vals > 1e8).any()
674+
has_small_values = ((abs_vals < 10**(-self.digits)) &
675+
(abs_vals > 0)).any()
672676

673677
if too_long and has_large_values:
674678
fmt_str = '%% .%de' % (self.digits - 1)
675679
fmt_values = self._format_with(fmt_str)
680+
elif has_small_values:
681+
fmt_str = '%% .%de' % (self.digits - 1)
682+
fmt_values = self._format_with(fmt_str)
676683

677684
return _make_fixed_width(fmt_values, self.justify)
678685

pandas/tests/test_format.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,24 @@ def test_to_string_float_formatting(self):
327327
'1 2.512000e-01')
328328
assert(df_s == expected)
329329

330+
def test_to_string_small_float_values(self):
331+
df = DataFrame({'a': [1.5, 1e-17, -5.5e-7]})
332+
333+
result = df.to_string()
334+
expected = (' a\n'
335+
'0 1.500000e+00\n'
336+
'1 1.000000e-17\n'
337+
'2 -5.500000e-07')
338+
self.assertEqual(result, expected)
339+
340+
# but not all exactly zero
341+
df = df * 0
342+
result = df.to_string()
343+
expected = (' 0\n'
344+
'0 0\n'
345+
'1 0\n'
346+
'2 -0')
347+
330348
def test_to_string_float_index(self):
331349
index = Index([1.5, 2, 3, 4, 5])
332350
df = DataFrame(range(5), index=index)

0 commit comments

Comments
 (0)