0

I am working with a DF similar to this one:

    A   B   C
0   1   4   7
1   2   5   8
2   3   6   9

I want the values of all columns to be stacked into the first column

Desired Output:

    A
0   1
1   2
2   3
3   4
4   5
5   6
6   7
7   8
8   9
Atharva Katre
  • 457
  • 1
  • 6
  • 17

4 Answers4

5

Very simply with melt:

import pandas as pd
df.melt().drop('variable',axis=1).rename({'value':'A'},axis=1)

   A
0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
sophocles
  • 13,593
  • 3
  • 14
  • 33
2

You can use .melt this will stack all of the columns on top of one another (see the "value" column) while also keeping track which column each value came from (specified by the "variable" column)

new_df = df.melt()

print(new_df)
  variable  value
0        A      1
1        A      2
2        A      3
3        B      4
4        B      5
5        B      6
6        C      7
7        C      8
8        C      9
Cameron Riddell
  • 10,942
  • 9
  • 19
2

Alternative to melt is unstack, and then drop the multilevel index

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

df.unstack().reset_index(drop=True)

yields:

0    1
1    2
2    3
3    4
4    5
5    6
6    7
7    8
8    9
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
1

Use the underlying numpy:

pd.DataFrame(df.values.T.ravel(), columns=['A'])

Output:

   A
0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74