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>You are misinterpreting what you are seeing.</p>

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

<p>Is not showing you a hierarchical column index.  <code>id</code> is the name of the row index.  In order to show you the name of the index, pandas is putting that space there for you.</p>

<p>The answer to your question depends on what you really want or need.</p>

<p>As the <code>df</code> is, you can dump it to a <code>csv</code> just the way you want:</p>

<pre><code>print(df.to_csv(sep='\t'))

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

<hr>

<pre><code>print(df.to_csv())

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

<hr>

<p>Or you can alter the <code>df</code> so that it displays the way you'd like</p>

<pre><code>print(df.rename_axis(None)) 

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

<hr>

<p><strong><em>please do not do this!!!!</em></strong><br>
I'm putting it to demonstrate how to manipulate</p>

<p>I could also keep the index as it is but manipulate both column and row index names to print how you would like.</p>

<pre><code>print(df.rename_axis(None).rename_axis('id', 1))

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

<p>But this has named the columns' index <code>id</code> which makes no sense.</p>

python pandas