Pandas dataframe rearrangement stack to two value columns (for factorplots)
<p>I have been trying to rearrange my dataframe to use it as input for a factorplot. The raw data would look like this:</p>

<pre><code>  A B C  D
1 0 1 2 "T"
2 1 2 3 "F"
3 2 1 0 "F"
4 1 0 2 "T"
...
</code></pre>

<p>My question is how can I rearrange it into this form:</p>

<pre><code>  col val val2
1  A   0  "T"
1  B   1  "T"
1  C   2  "T"
2  A   1  "F"
...
</code></pre>

<p>I was trying:</p>

<pre><code>df = DF.cumsum(axis=0).stack().reset_index(name="val")
</code></pre>

<p>However this produces only one value column not two.. thanks for your support</p>

<p>consider your dataframe <code>df</code></p>

<pre><code>df = pd.DataFrame([
        [0, 1, 2, 'T'],
        [1, 2, 3, 'F'],
        [2, 1, 3, 'F'],
        [1, 0, 2, 'T'],
    ], [1, 2, 3, 4], list('ABCD'))
</code></pre>

<p><a href="http://i.stack.imgur.com/XtqBK.png" rel="nofollow"><img src="http://i.stack.imgur.com/XtqBK.png" alt="enter image description here"></a></p>

<p><strong><em>solution</em></strong></p>

<pre><code>df.set_index('D', append=True) \
    .rename_axis(['col'], 1) \
    .rename_axis([None, 'val2']) \
    .stack().to_frame('val') \
    .reset_index(['col', 'val2']) \
    [['col', 'val', 'val2']]
</code></pre>

<p><a href="http://i.stack.imgur.com/RRNtS.png" rel="nofollow"><img src="http://i.stack.imgur.com/RRNtS.png" alt="enter image description here"></a></p>

python pandas stack cumsum