Skip to content

Commit c481793

Browse files
committed
BUG: hack around Series mixed-type formatting issue, GH #616
1 parent 4ef29e4 commit c481793

File tree

2 files changed

+38
-8
lines changed

2 files changed

+38
-8
lines changed

pandas/core/series.py

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -522,19 +522,31 @@ def _get_repr(self, name=False, print_header=False, length=True,
522522
if float_format is None:
523523
float_format = com._float_format_default
524524

525-
def _format(k, v):
525+
def _format(k, v, extra=0):
526526
# GH #490
527527
if not isinstance(v, np.ndarray) and isnull(v):
528528
v = na_rep
529529
if com.is_float(v):
530530
v = float_format(v)
531-
return '%s %s' % (str(k).ljust(padSpace),
532-
str(v).replace('\n', ' '))
533-
534-
it = [_format(idx, v) for idx, v in izip(string_index, vals)]
531+
strv = ' ' * extra + str(v).replace('\n', ' ')
532+
return '%s %s' % (str(k).ljust(padSpace), strv)
533+
534+
# floating point handling
535+
if self.dtype == 'O':
536+
is_float = (self.map(com.is_float) & self.notnull()).values
537+
leading_space = is_float.any()
538+
539+
res = []
540+
for i, (k, v) in enumerate(izip(string_index, vals)):
541+
if not is_float[i] and leading_space:
542+
res.append(_format(k, v, extra=1))
543+
else:
544+
res.append(_format(k, v))
545+
else:
546+
res = [_format(idx, v) for idx, v in izip(string_index, vals)]
535547

536548
if print_header and have_header:
537-
it.insert(0, header)
549+
res.insert(0, header)
538550

539551
footer = ''
540552
if name:
@@ -546,9 +558,9 @@ def _format(k, v):
546558
footer += 'Length: %d' % len(self)
547559

548560
if footer:
549-
it.append(footer)
561+
res.append(footer)
550562

551-
return '\n'.join(it)
563+
return '\n'.join(res)
552564

553565
def __str__(self):
554566
return repr(self)

pandas/tests/test_series.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -608,6 +608,24 @@ def test_to_string(self):
608608
last_line = result.split('\n')[-1].strip()
609609
self.assertEqual(last_line, "Name: foo, Length: %d" % len(cp))
610610

611+
def test_to_string_mixed(self):
612+
s = Series(['foo', np.nan, -1.23, 4.56])
613+
result = s.to_string()
614+
expected = ('0 foo\n'
615+
'1 NaN\n'
616+
'2 -1.23\n'
617+
'3 4.56')
618+
self.assertEqual(result, expected)
619+
620+
# but don't count NAs as floats
621+
s = Series(['foo', np.nan, 'bar', 'baz'])
622+
result = s.to_string()
623+
expected = ('0 foo\n'
624+
'1 NaN\n'
625+
'2 bar\n'
626+
'3 baz')
627+
self.assertEqual(result, expected)
628+
611629
def test_iter(self):
612630
for i, val in enumerate(self.series):
613631
self.assertEqual(val, self.series[i])

0 commit comments

Comments
 (0)