Home > Mobile >  How to merge columns vertically?
How to merge columns vertically?

Time:11-26

Hi I have a df with columns that looks like this:

              E              F              G
0  10516894 0000  10523438 0000  10531813 0003
1  10334414 0007  12082512 0000  12058004 0004
2             05             00             03
3             07             00             04
4             02             08             05

But I want it like this, all in one column:

              E              
0  10516894 0000 
1  10334414 0007 
2          05 
3          07 
4          02 
5  10523438 0000
6  12082512 0000
7          00
8          00
9          08
10 10531813 0003
11 12058004 0004
12         03
13         04
14         05

Im quite new to pandas so I'm not sure the best way to go about this.

CodePudding user response:

Use DataFrame.unstack:

df = df.unstack().to_frame('E').reset_index(drop=True) 
print (df)
                E
0   10516894 0000
1   10334414 0007
2              05
3              07
4              02
5   10523438 0000
6   12082512 0000
7              00
8              00
9              08
10  10531813 0003
11  12058004 0004
12             03
13             04
14             05

Or DataFrame.melt with set new column name by value_name:

df = df.melt(value_name='E')[['E']]
print (df)
                E
0   10516894 0000
1   10334414 0007
2              05
3              07
4              02
5   10523438 0000
6   12082512 0000
7              00
8              00
9              08
10  10531813 0003
11  12058004 0004
12             03
13             04
14             05

CodePudding user response:

You can use df.melt:

  df.melt()['value']
  • Related