combine multiple column into one in pandas

Question:

I have table like below

  Column 1  Column 2   Column 3 ...
0        a         1          2
1        b         1          3
2        c         2          1

and I want to convert it to be like below

  Column 1 Column 2
0        a        1
1        a        2
2        b        1
3        b        3
4        c        2
5        c        1
...

I want to take each value from Column 2 (and so on) and pair it to value in column 1. I have no idea how to do it in pandas or even where to start.

Asked By: nama asliku

||

Answers:

You can use pd.melt to do this:

>>> df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},
...                    'B': {0: 1, 1: 3, 2: 5},
...                    'C': {0: 2, 1: 4, 2: 6}})

>>> df

   A  B  C
0  a  1  2
1  b  3  4
2  c  5  6

>>> pd.melt(df, id_vars=['A'], value_vars=['B', 'C'])

   A variable  value
0  a        B      1
1  b        B      3
2  c        B      5
3  a        C      2
4  b        C      4
5  c        C      6
Answered By: Daniel Lenz

Here’s my approach, hope it helps:

import pandas as pd
df=pd.DataFrame({'col1':['a','b','c'],'col2':[1,1,2],'col3':[2,3,1]})

new_df=pd.DataFrame(columns=['col1','col2'])
for index,row in df.iterrows():
    for element in row.values[1:]:
        new_df.loc[len(new_df)]=[row[0],element]
print(new_df)
Output:
  col1  col2
0    a     1
1    a     2
2    b     1
3    b     3
4    c     2
5    c     1
Answered By: HelloWorld
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.