Repository: pandas-dev/pandas

Issue:
to_latex wrong \multicolumn count
#### Code Sample

```python
import pandas as pd

pd.DataFrame({"A":[1,2,3]}).to_latex(longtable=True)
```
#### Problem description

```
\begin{longtable}{lr}
\toprule
{} &  A \\
\midrule
\endhead
\midrule
\multicolumn{3}{r}{{Continued on next page}} \\
\midrule
\endfoot

\bottomrule
\endlastfoot
0 &  1 \\
1 &  2 \\
2 &  3 \\
\end{longtable}
```

It says ```\multicolumn{3}``` but it should be 2, it only fails with ```longtable=True```. Indeed it always writes 3 no matter what shape the table has.

#### Expected Output
```
\multicolumn{2}
```

#### Output of ``pd.show_versions()``

<details>
INSTALLED VERSIONS
------------------
commit: None
python: 3.5.2.final.0
python-bits: 64
OS: Linux
OS-release: 4.10.0-35-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.20.1
pytest: None
pip: 9.0.1
setuptools: 20.7.0
Cython: None
numpy: 1.12.1
scipy: 0.19.0
xarray: None
IPython: 6.1.0
sphinx: None
patsy: 0.4.1
dateutil: 2.6.0
pytz: 2013b
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 2.0.0
openpyxl: None
xlrd: 1.0.0
xlwt: None
xlsxwriter: 0.7.3
lxml: None
bs4: None
html5lib: 0.999999999
sqlalchemy: None
pymysql: None
psycopg2: 2.7.1 (dt dec pq3 ext lo64)
jinja2: 2.8
s3fs: None
pandas_gbq: None
pandas_datareader: None
</details>



Discussion:
> Indeed it always writes 3 no matter what shape the table has.

I'm not sure that should be the case...that being said, feel free to investigate and figure out the cause.
https://github.com/pandas-dev/pandas/blob/3c964a47d626a06a3f9c2d0795ee7d744dc72363/pandas/io/formats/format.py#L945
line 945, the 3 is fixed, it might should be ```len(rows)```

The testcase says also 3 line
368: ```\multicolumn{3}{r}{{Continued on next page}} \\```
https://github.com/pandas-dev/pandas/blob/6b729ddd740b6d2efb739757180dbbbef9b092c7/pandas/tests/io/formats/test_to_latex.py#L368

If I change it the test won't work but I dont think that the test is correct.
Not sure why we are using hard-coded values.  Let's change to it (both in the source code and tests) to vary, and let's see how the output looks like when we do that.

(BTW, when I say "see how the output looks", I mean that we should also make sure that it renders properly when converted to PDF for example - that would have to be done somewhat manually)

Resolving patch:
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -962,8 +962,8 @@ def get_col_type(dtype):
                 if self.longtable:
                     buf.write('\\endhead\n')
                     buf.write('\\midrule\n')
-                    buf.write('\\multicolumn{3}{r}{{Continued on next '
-                              'page}} \\\\\n')
+                    buf.write('\\multicolumn{{{n}}}{{r}}{{{{Continued on next '
+                              'page}}}} \\\\\n'.format(n=len(row)))
                     buf.write('\\midrule\n')
                     buf.write('\\endfoot\n\n')
                     buf.write('\\bottomrule\n')


Test patch:
diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py
--- a/pandas/tests/io/formats/test_to_latex.py
+++ b/pandas/tests/io/formats/test_to_latex.py
@@ -91,6 +91,29 @@ def test_to_latex_format(self, frame):
 
         assert withindex_result == withindex_expected
 
+    def test_to_latex_empty(self):
+        df = DataFrame()
+        result = df.to_latex()
+        expected = r"""\begin{tabular}{l}
+\toprule
+Empty DataFrame
+Columns: Index([], dtype='object')
+Index: Index([], dtype='object') \\
+\bottomrule
+\end{tabular}
+"""
+        assert result == expected
+
+        result = df.to_latex(longtable=True)
+        expected = r"""\begin{longtable}{l}
+\toprule
+Empty DataFrame
+Columns: Index([], dtype='object')
+Index: Index([], dtype='object') \\
+\end{longtable}
+"""
+        assert result == expected
+
     def test_to_latex_with_formatters(self):
         df = DataFrame({'int': [1, 2, 3],
                         'float': [1.0, 2.0, 3.0],
@@ -377,7 +400,7 @@ def test_to_latex_longtable(self, frame):
 1 &  2 &  b2 \\
 \end{longtable}
 """
-
+        open("expected.txt", "w").write(withindex_result)
         assert withindex_result == withindex_expected
 
         withoutindex_result = df.to_latex(index=False, longtable=True)
@@ -387,7 +410,7 @@ def test_to_latex_longtable(self, frame):
 \midrule
 \endhead
 \midrule
-\multicolumn{3}{r}{{Continued on next page}} \\
+\multicolumn{2}{r}{{Continued on next page}} \\
 \midrule
 \endfoot
 
@@ -400,6 +423,14 @@ def test_to_latex_longtable(self, frame):
 
         assert withoutindex_result == withoutindex_expected
 
+        df = DataFrame({'a': [1, 2]})
+        with1column_result = df.to_latex(index=False, longtable=True)
+        assert "\multicolumn{1}" in with1column_result
+
+        df = DataFrame({'a': [1, 2], 'b': [3, 4], 'c': [5, 6]})
+        with3columns_result = df.to_latex(index=False, longtable=True)
+        assert "\multicolumn{3}" in with3columns_result
+
     def test_to_latex_escape_special_chars(self):
         special_characters = ['&', '%', '$', '#', '_', '{', '}', '~', '^',
                               '\\']