Skip to content

Commit f430201

Browse files
committed
ENH: add float_format option to Series.to_string, GH #333
1 parent 2c73bc1 commit f430201

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

pandas/core/series.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -356,21 +356,21 @@ def _tidy_repr(self, max_vals=20):
356356
result = '%s\n%sLength: %d' % (result, namestr, len(self))
357357
return result
358358

359-
def to_string(self, buf=None, na_rep='NaN', nanRep=None):
359+
def to_string(self, buf=None, na_rep='NaN', float_format=None, nanRep=None):
360360
if nanRep is not None: # pragma: no cover
361361
import warnings
362362
warnings.warn("nanRep is deprecated, use na_rep",
363363
FutureWarning)
364364
na_rep = nanRep
365365

366-
the_repr = self._get_repr(na_rep=na_rep)
366+
the_repr = self._get_repr(float_format=float_format, na_rep=na_rep)
367367
if buf is None:
368368
return the_repr
369369
else:
370370
print >> buf, the_repr
371371

372372
def _get_repr(self, name=False, print_header=False, length=True,
373-
na_rep='NaN'):
373+
na_rep='NaN', float_format=None):
374374
vals = self.values
375375
index = self.index
376376

@@ -387,9 +387,14 @@ def _get_repr(self, name=False, print_header=False, length=True,
387387
maxlen = max(len(x) for x in string_index)
388388
padSpace = min(maxlen, 60)
389389

390+
if float_format is None:
391+
float_format = str
392+
390393
def _format(k, v):
391394
if isnull(v):
392395
v = na_rep
396+
if isinstance(v, (float, np.floating)):
397+
v = float_format(v)
393398
return '%s %s' % (str(k).ljust(padSpace), v)
394399

395400
it = [_format(idx, v) for idx, v in izip(string_index, vals)]

pandas/tests/test_series.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,13 @@ def test_to_string(self):
488488
self.assert_(retval is None)
489489
self.assertEqual(buf.getvalue().strip(), s)
490490

491+
# pass float_format
492+
format = '%.4f'.__mod__
493+
result = self.ts.to_string(float_format=format)
494+
result = [x.split()[1] for x in result.split('\n')[:-1]]
495+
expected = [format(x) for x in self.ts]
496+
self.assertEqual(result, expected)
497+
491498
def test_iter(self):
492499
for i, val in enumerate(self.series):
493500
self.assertEqual(val, self.series[i])

0 commit comments

Comments
 (0)