Repository: statsmodels/statsmodels

Issue:
BUG: Lagmat fails when pandas DataFrame has RangeIndex
When passing a pandas DataFrame to lagmat() function, a KeyError is raised if the columns have a RangeIndex. 

#### Code Sample
```python
from statsmodels.tsa.tsatools import lagmat
from numpy import r_
from pandas import DataFrame

# Works
my_other_data = DataFrame(r_[0:10].reshape(5,2), columns=['A', 'B'])
print(my_other_data)

my_other_lagmat = lagmat(my_other_data, maxlag=2, use_pandas=True)
print(my_other_lagmat)

# Fails
my_data = DataFrame(r_[0:10].reshape(5,2))
print(my_data)

my_lagmat = lagmat(my_data, maxlag=2, use_pandas=True) # KeyError
print(my_lagmat)
```

#### Expected Output
The function should succeed for any valid pandas DataFrame. :-)

#### Output of ``import statsmodels.api as sm; sm.show_versions()``

<details>

INSTALLED VERSIONS
------------------
Python: 3.10.4.final.0
OS: Linux 5.15.0-46-generic #49-Ubuntu SMP Thu Aug 4 xx:xx:xx UTC 2022 x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8

statsmodels
===========

Installed: 0.13.2 (/home/user/path_to_venv/lib/python3.10/site-packages/statsmodels)

Required Dependencies
=====================

cython: Not installed
numpy: 1.23.1 (/home/user/path_to_venv/lib/python3.10/site-packages/numpy)
scipy: 1.9.0 (/home/user/path_to_venv/lib/python3.10/site-packages/scipy)
pandas: 1.4.3 (/home/user/path_to_venv/lib/python3.10/site-packages/pandas)
    dateutil: 2.8.2 (/home/user/path_to_venv/lib/python3.10/site-packages/dateutil)
patsy: 0.5.2 (/home/user/path_to_venv/lib/python3.10/site-packages/patsy)

Optional Dependencies
=====================

matplotlib: 3.5.2 (/home/user/path_to_venv/lib/python3.10/site-packages/matplotlib)
    backend: module://matplotlib_inline.backend_inline 
cvxopt: Not installed
joblib: 1.1.0 (/home/user/path_to_venv/lib/python3.10/site-packages/joblib)

Developer Tools
================

IPython: 8.4.0 (/home/user/path_to_venv/lib/python3.10/site-packages/IPython)
    jinja2: Not installed
sphinx: Not installed
    pygments: 2.12.0 (/home/user/path_to_venv/lib/python3.10/site-packages/pygments)
pytest: Not installed
virtualenv: Not installed




</details>


Discussion:

Patch:
diff --git a/statsmodels/tsa/tsatools.py b/statsmodels/tsa/tsatools.py
index 5a67b8e2b..a728e1500 100644
--- a/statsmodels/tsa/tsatools.py
+++ b/statsmodels/tsa/tsatools.py
@@ -397,8 +397,8 @@ def lagmat(x,
     lm = np.zeros((nobs + maxlag, nvar * (maxlag + 1)))
     for k in range(0, int(maxlag + 1)):
         lm[
-            maxlag - k : nobs + maxlag - k,
-            nvar * (maxlag - k) : nvar * (maxlag - k + 1),
+        maxlag - k: nobs + maxlag - k,
+        nvar * (maxlag - k): nvar * (maxlag - k + 1),
         ] = x
 
     if trim in ("none", "forward"):
@@ -415,7 +415,15 @@ def lagmat(x,
 
     if is_pandas:
         x = orig
-        x_columns = x.columns if isinstance(x, DataFrame) else [x.name]
+        if isinstance(x, DataFrame):
+            x_columns = [str(c) for c in x.columns]
+            if len(set(x_columns)) != x.shape[1]:
+                raise ValueError(
+                    "Columns names must be distinct after conversion to string "
+                    "(if not already strings)."
+                )
+        else:
+            x_columns = [str(x.name)]
         columns = [str(col) for col in x_columns]
         for lag in range(maxlag):
             lag_str = str(lag + 1)


Test patch:
diff --git a/statsmodels/regression/tests/test_regression.py b/statsmodels/regression/tests/test_regression.py
index db8eb2eee..31576d416 100644
--- a/statsmodels/regression/tests/test_regression.py
+++ b/statsmodels/regression/tests/test_regression.py
@@ -651,6 +651,7 @@ class TestGLS_alt_sigma(CheckRegressionResults):
             sigma=np.ones((n - 1, n - 1)),
         )
 
+    @pytest.mark.skip("Test does not raise but should")
     def test_singular_sigma(self):
         n = len(self.endog)
         sigma = np.ones((n, n)) + np.diag(np.ones(n))
diff --git a/statsmodels/tsa/tests/test_tsa_tools.py b/statsmodels/tsa/tests/test_tsa_tools.py
index 93fb4de4b..e48084965 100644
--- a/statsmodels/tsa/tests/test_tsa_tools.py
+++ b/statsmodels/tsa/tests/test_tsa_tools.py
@@ -449,6 +449,21 @@ class TestLagmat:
         assert_frame_equal(lead, expected.iloc[:, :1])
         assert_frame_equal(lags, expected.iloc[:, 1:])
 
+    def test_range_index_columns(self):
+        # GH 8377
+        df = pd.DataFrame(np.arange(200).reshape((-1, 2)))
+        df.columns = pd.RangeIndex(2)
+        result = stattools.lagmat(df, maxlag=2, use_pandas=True)
+        assert result.shape == (100, 4)
+        assert list(result.columns) == ["0.L.1", "1.L.1", "0.L.2", "1.L.2"]
+
+    def test_duplicate_column_names(self):
+        # GH 8377
+        df = pd.DataFrame(np.arange(200).reshape((-1, 2)))
+        df.columns = [0, "0"]
+        with pytest.raises(ValueError, match="Columns names must be"):
+            stattools.lagmat(df, maxlag=2, use_pandas=True)
+
 
 def test_freq_to_period():
     from pandas.tseries.frequencies import to_offset