Create unique MultiIndex from Non-unique Index Python Pandas
<p>I have a pandas DataFrame with a non-unique index:</p>

<pre><code>index = [1,1,1,1,2,2,2,3]

df = pd.DataFrame(data = {'col1': [1,3,7,6,2,4,3,4]}, index=index)

df
Out[12]: 
   col1
1     1
1     3
1     7
1     6
2     2
2     4
2     3
3     4
</code></pre>

<p>I'd like to turn this into unique MultiIndex and preserve order, like this:</p>

<pre><code>        col1
  Ind2      
1 0        1
  1        3
  2        7
  3        6
2 0        2
  1        4
  2        3
3 0        4
</code></pre>

<p>I would imagine pandas would have a function for something like this but haven't found anything</p>

<p>You can do a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>groupby.cumcount</code></a> on the index, and then append it as a new level to the index using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a>:</p>

<pre><code>df = df.set_index(df.groupby(level=0).cumcount(), append=True)
</code></pre>

<p>The resulting output:</p>

<pre><code>     col1
1 0     1
  1     3
  2     7
  3     6
2 0     2
  1     4
  2     3
3 0     4
</code></pre>

python pandas