diff --git a/doc/source/io.rst b/doc/source/io.rst index f74120ad7ef57..3fbc45dda8fa4 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -668,7 +668,7 @@ over the string representation of the object. All arguments are optional: - ``buf`` default None, for example a StringIO object - ``columns`` default None, which columns to write - - ``col_space`` default None, number of spaces to write between columns + - ``col_space`` default None, minimum width of each column. - ``na_rep`` default ``NaN``, representation of NA value - ``formatters`` default None, a dictionary (by column) of functions each of which takes a single argument and returns a formatted string diff --git a/pandas/core/format.py b/pandas/core/format.py index 13e504a8e1f88..841500329d4a9 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -27,7 +27,7 @@ columns : sequence, optional the subset of columns to write; default None writes all columns col_space : int, optional - the width of each columns + the minimum width of each column header : bool, optional whether to print column labels, default True index : bool, optional @@ -215,7 +215,7 @@ def _to_str_columns(self, force_unicode=False): fmt_values = self._format_col(i) cheader = str_columns[i] - max_colwidth = max(_strlen(x) for x in cheader) + max_colwidth = max(self.col_space or 0, *(_strlen(x) for x in cheader)) fmt_values = _make_fixed_width(fmt_values, self.justify, minimum=max_colwidth) @@ -434,6 +434,11 @@ def write(self, s, indent=0): self.elements.append(' ' * indent + com.pprint_thing(s)) def write_th(self, s, indent=0, tags=None): + if (self.fmt.col_space is not None + and self.fmt.col_space > 0 ): + tags = (tags or "" ) + tags += 'style="min-width: %s;"' % self.fmt.col_space + return self._write_cell(s, kind='th', indent=indent, tags=tags) def write_td(self, s, indent=0, tags=None): diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index 10bb75bfbb5b6..8d0dacf2e7edd 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -182,6 +182,30 @@ def test_to_string_buffer_all_unicode(self): # this should work buf.getvalue() + def test_to_string_with_col_space(self): + df = DataFrame(np.random.random(size=(1,3))) + c10=len(df.to_string(col_space=10).split("\n")[1]) + c20=len(df.to_string(col_space=20).split("\n")[1]) + c30=len(df.to_string(col_space=30).split("\n")[1]) + self.assertTrue( c10 < c20 < c30 ) + + def test_to_html_with_col_space(self): + def check_with_width(df,col_space): + import re + # check that col_space affects HTML generation + # and be very brittle about it. + html = df.to_html(col_space=col_space) + hdrs = [x for x in html.split("\n") if re.search("