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>I would use melt, and you can sort it how ever you like</p>

<pre><code>pd.melt(df.reset_index(),id_vars=['index','D'], value_vars=['A','B','C']).sort_values(by='index')
Out[40]: 
    index  D variable  value
0       1  T        A      0
4       1  T        B      1
8       1  T        C      2
1       2  F        A      1
5       2  F        B      2
9       2  F        C      3
2       3  F        A      2
6       3  F        B      1
10      3  F        C      0
3       4  T        A      1
7       4  T        B      0
11      4  T        C      2
</code></pre>

<p>then obviously you can name column as you like</p>

<pre><code>df.set_index('index').rename(columns={'D': 'col', 'variable': 'val2', 'value': 'val'})
</code></pre>

python pandas stack cumsum