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>Given:</p>

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

<p>For printing purdy, you can produce a copy of the DataFrame with a reset the index and use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_string.html" rel="nofollow">.to_string</a>:</p>

<pre><code>&gt;&gt;&gt; print df2.reset_index().to_string(index=False)
id  A  B
101  3  x
102  5  y
</code></pre>

<p>Then play around with the formatting options so that the output suites your needs:</p>

<pre><code>&gt;&gt;&gt; fmts=[lambda s: u"{:^5}".format(str(s).strip())]*3
&gt;&gt;&gt; print df2.reset_index().to_string(index=False, formatters=fmts)
id     A      B
101    3      x  
102    5      y
</code></pre>

python pandas