Pandas: how to convert an M*N dataframe to an (M*N)*1 dataframe

Suppose I have a 2*3 dataframe:

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4], 'C': [5, 6]})

    A   B   C
0   1   3   5
1   2   4   6

I’m wondering how can I convert df to a (2*3)*1 dataframe that has the following form? I’ve tried pd.DataFrame.explode() and pd.wide_to_long() but they didn’t appear to be the function I’m looking for.

        value
A   0       1   
A   1       2   
B   0       3
B   1       4
C   0       5
C   1       6

Answer

You just need to stack:

df.stack().swaplevel().sort_index()

output:

A  0    1
   1    2
B  0    3
   1    4
C  0    5
   1    6

Or use melt after resetting the index:

df.reset_index().melt(id_vars='index')

output:

   index variable  value
0      0        A      1
1      1        A      2
2      0        B      3
3      1        B      4
4      0        C      5
5      1        C      6

Alternative outputs

As dataframe:

(df.stack()
   .rename('value')
   .swaplevel()
   .sort_index()
   .to_frame()
)
     value
A 0      1
  1      2
B 0      3
  1      4
C 0      5
  1      6

All as columns:

(df.stack()
   .rename('value')
   .swaplevel()
   .rename_axis(['col1', 'col2'])
   .sort_index()
   .reset_index()
)
  col1  col2  value
0    A     0      1
1    A     1      2
2    B     0      3
3    B     1      4
4    C     0      5
5    C     1      6