Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Multiple columns into one column

Tags:

I have the following data (2 columns, 4 rows):

Column 1: A, B, C, D  Column 2: E, F, G, H 

I am attempting to combine the columns into one column to look like this (1 column, 8 rows):

Column 3: A, B, C, D, E, F, G, H 

I am using pandas DataFrame and have tried using different functions with no success (append, concat, etc.). Any help would be most appreciated!

like image 242
user2929063 Avatar asked May 01 '14 14:05

user2929063


People also ask

How do I make multiple columns in one column in pandas?

If you want to concatenate new columns by splitting and some columns of original DataFrame to a new DataFrame, you can use concat() method of Pandas. concat() accepts a list of DataFrame, axis=1 means concatenate DataFrames in horizontal direction.

How do I merge 3 columns in pandas?

To merge two pandas DataFrames on multiple columns use pandas. merge() method. merge() is considered more versatile and flexible and we also have the same method in DataFrame.


2 Answers

The trick is to use stack()

df.stack().reset_index()         level_0   level_1  0 0        0  Column 1  A 1        0  Column 2  E 2        1  Column 1  B 3        1  Column 2  F 4        2  Column 1  C 5        2  Column 2  G 6        3  Column 1  D 7        3  Column 2  H 
like image 194
Nickpick Avatar answered Oct 22 '22 14:10

Nickpick


Update

pandas has a built in method for this stack which does what you want see the other answer.

This was my first answer before I knew about stack many years ago:

In [227]:  df = pd.DataFrame({'Column 1':['A', 'B', 'C', 'D'],'Column 2':['E', 'F', 'G', 'H']}) df Out[227]:   Column 1 Column 2 0        A        E 1        B        F 2        C        G 3        D        H  [4 rows x 2 columns]  In [228]:  df['Column 1'].append(df['Column 2']).reset_index(drop=True) Out[228]: 0    A 1    B 2    C 3    D 4    E 5    F 6    G 7    H dtype: object 
like image 43
EdChum Avatar answered Oct 22 '22 15:10

EdChum