Pandas flatten hierarchical index on non overlapping columns
<p>I have a dataframe, and I set the index to a column of the dataframe. This creates a hierarchical column index. I want to flatten the columns to a single level. Similar to this question - <a href="http://stackoverflow.com/questions/14507794/python-pandas-how-to-flatten-a-hierarchical-index-in-columns">Python Pandas - How to flatten a hierarchical index in columns</a>, however, the columns do not overlap (i.e. 'id' is not at level 0 of the hierarchical index, and other columns are at level 1 of the index).</p>

<pre><code>df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B'])
df.set_index('id', inplace=True)

      A    B
id
101   3    x
102   5    y
</code></pre>

<p>Desired output is flattened columns, like this:</p>

<pre><code>id    A    B
101   3    x
102   5    y
</code></pre>

<p>there will always be an index in your dataframes. if you don't set 'id' as index, it will be at the same level as other columns and pandas will populate an increasing integer for your index starting from 0.</p>

<pre><code>df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B'])

In[52]: df
Out[52]: 
    id  A  B
0  101  3  x
1  102  5  y
</code></pre>

<p>the index is there so you can slice the original dataframe. such has</p>

<pre><code>df.iloc[0]
Out[53]: 
id    101
A       3
B       x
Name: 0, dtype: object
</code></pre>

<p>so let says you want ID as index and ID as a column, which is very redundant, you could do:</p>

<pre><code>df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B'])
df.set_index('id', inplace=True)
df['id'] = df.index
df
Out[55]: 
     A  B   id
id            
101  3  x  101
102  5  y  102
</code></pre>

<p>with this you can slice by 'id' such has:</p>

<pre><code>df.loc[101]
Out[57]: 
A       3
B       x
id    101
Name: 101, dtype: object
</code></pre>

<p>but it would the same info has :</p>

<pre><code>df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B'])
df.set_index('id', inplace=True)
df.loc[101]

Out[58]: 
A    3
B    x
Name: 101, dtype: object
</code></pre>

python pandas