diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 0ec9758477eba..fcfac2d2d63f1 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -740,6 +740,7 @@ I/O - Bug in :func:`read_hdf` returning unexpected records when filtering on categorical string columns using ``where`` parameter (:issue:`39189`) - Bug in :func:`read_sas` raising ``ValueError`` when ``datetimes`` were null (:issue:`39725`) - Bug in :func:`read_excel` dropping empty values from single-column spreadsheets (:issue:`39808`) +- Bug in :meth:`DataFrame.to_string` misplacing the truncation column when ``index=False`` (:issue:`40907`) Period ^^^^^^ diff --git a/pandas/io/formats/string.py b/pandas/io/formats/string.py index 84333cfc441b2..de53646b5f95f 100644 --- a/pandas/io/formats/string.py +++ b/pandas/io/formats/string.py @@ -77,7 +77,8 @@ def _insert_dot_separators(self, strcols: List[List[str]]) -> List[List[str]]: def _insert_dot_separator_horizontal( self, strcols: List[List[str]], index_length: int ) -> List[List[str]]: - strcols.insert(self.fmt.tr_col_num + 1, [" ..."] * index_length) + tr_col_num = self.fmt.tr_col_num + 1 if self.fmt.index else self.fmt.tr_col_num + strcols.insert(tr_col_num, [" ..."] * index_length) return strcols def _insert_dot_separator_vertical( diff --git a/pandas/tests/io/formats/test_to_string.py b/pandas/tests/io/formats/test_to_string.py index 551734f343dfa..f9b3cac3527ef 100644 --- a/pandas/tests/io/formats/test_to_string.py +++ b/pandas/tests/io/formats/test_to_string.py @@ -106,6 +106,40 @@ def test_format_remove_leading_space_dataframe(input_array, expected): assert df == expected +@pytest.mark.parametrize( + "max_cols, expected", + [ + ( + 10, + [ + " 0 1 2 3 4 ... 6 7 8 9 10", + " 0 0 0 0 0 ... 0 0 0 0 0", + " 0 0 0 0 0 ... 0 0 0 0 0", + ], + ), + ( + 9, + [ + " 0 1 2 3 ... 7 8 9 10", + " 0 0 0 0 ... 0 0 0 0", + " 0 0 0 0 ... 0 0 0 0", + ], + ), + ( + 1, + [ + " 0 ...", + " 0 ...", + " 0 ...", + ], + ), + ], +) +def test_truncation_col_placement_no_index(max_cols, expected): + df = DataFrame([[0] * 11] * 2) + assert df.to_string(index=False, max_cols=max_cols).split("\n") == expected + + def test_to_string_unicode_columns(float_frame): df = DataFrame({"\u03c3": np.arange(10.0)})