pandas adding columns to bottom of column

Viewed 504

I have a df = pd.DataFrame([[1, 3, 5], [2, 4, 6]]) that looks like

    0   1   2
0   1   3   5
1   2   4   6

I am trying to move each of the columns to the bottom of the first column. It should look something like...

    0
0   1
1   2
2   3
3   4
4   5
5   6

Looking for a way to do this with n rows on a much larger dataframe. I was looking for other ways with pandas stack() but have not found a solution.

2 Answers

You could transpose and stack:

import pandas as pd

df = pd.DataFrame([[1, 3, 5], [2, 4, 6]])
res = df.T.stack()
print(res)

Output

0  0    1
   1    2
1  0    3
   1    4
2  0    5
   1    6
dtype: int64

If you want to remove the index, use reset_index (as suggested by @JoeFerndz):

res = df.T.stack().reset_index(drop=True)
print(res)

Output

0    1
1    2
2    3
3    4
4    5
5    6
dtype: int64

As an alternative, just flatten the numpy array directly:

res = pd.DataFrame(df.values.flatten('F'))
print(res)

Output

   0
0  1
1  2
2  3
3  4
4  5
5  6

The F means:

to flatten in column-major (Fortran- style) order.

This can be done using Numpy's reshape method. The code below first converts the DataFrame to a Numpy array and then reshapes it to a column array by traversing the elements in Fortran-like index order. The result is finally converted back to a Pandas DataFrame.

pd.DataFrame(df.values.reshape((-1, 1), order="F"))
Related