0

Example Pandas DataFrame

How do you combine all the rows in all columns into a single column? I would like to append the rows in C2 and C3 to C1. That is, have one column, C1, with 15 rows, each with their respective values.

T. Bill
  • 11
  • 1
  • 1
  • 6
  • 1
    Please include any code and errors as formatted text not images meta.https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557 – Geneva Mar 04 '22 at 02:32
  • 1
    similar question: https://stackoverflow.com/questions/34376053/pandas-dataframe-stack-multiple-column-values-into-single-column – Geneva Mar 04 '22 at 02:45

2 Answers2

0

One way is to create a new DataFrame from the reshaped numpy array underlying the original DataFrame, using order='F' to stack columns on top of each other:

df_new = pd.DataFrame(df.to_numpy().reshape(-1, 1, order='F'), 
                      columns=['C1'])

Relevant section of the numpy.reshape documentation:

order : {‘C’, ‘F’, ‘A’}, optional

Read the elements of a using this index order, and place the elements into the reshaped array using this index order. ‘C’ means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest

Peter Leimbigler
  • 10,775
  • 1
  • 23
  • 37
0

One way is to use pd.DataFrame.melt:

df.melt()

Output:

   variable value
0        C1     A
1        C1     B
2        C1     C
3        C1     D
4        C1     E
5        C2     F
6        C2     G
7        C2     H
8        C2     I
9        C2     J
10       C3     K
11       C3     L
12       C3     M
13       C3     N
14       C3     O   
Scott Boston
  • 147,308
  • 15
  • 139
  • 187