2

I need to append two columns into one and separate them with an empty row

this is the current code (inspired by this question) :

import pandas as pd

df = pd.DataFrame({'Column 1':['A', 'B', 'C', 'D'],'Column 2':['E', 'F', 'G', 'H'],'Column 3':['I', 'J', 'K', 'L']})
df['col']=df['Column 1'].append(df['Column 2']).reset_index(drop=True)
print(df) 

output:

  Column 1 Column 2 Column 3 col
0        A        E        I   A
1        B        F        J   B
2        C        G        K   C
3        D        H        L   D

desired output:

  Column 1 Column 2 Column 3 col
0        A        E        I   A
1        B        F        J   B
2        C        G        K   C
3        D        H        L   D
4      nan      nan      nan nan
5      nan      nan      nan   E
6      nan      nan      nan   F
7      nan      nan      nan   G
8      nan      nan      nan   H

is it doable?

newbie
  • 646
  • 8
  • 27

3 Answers3

4

My idea is to use pandas.concat:

import pandas as pd

df = pd.DataFrame({'Column 1':['A', 'B', 'C', 'D'],'Column 2':['E', 'F', 'G', 'H'],'Column 3':['I', 'J', 'K', 'L']})
col = df['Column 1'].append(pd.Series(float('nan'))).append(df['Column 2']).reset_index(drop=True)

df = pd.concat([df, col], axis=1)

print(df)

  Column 1 Column 2 Column 3    0
0        A        E        I    A
1        B        F        J    B
2        C        G        K    C
3        D        H        L    D
4      NaN      NaN      NaN  NaN
5      NaN      NaN      NaN    E
6      NaN      NaN      NaN    F
7      NaN      NaN      NaN    G
8      NaN      NaN      NaN    H
Paweł Kowalski
  • 524
  • 3
  • 9
3

Yes it can be done

df['col']=df['Column 1']
df=df.append(pd.DataFrame({'Column 2':[np.nan]}).append(df[['Column 2']]).rename(columns={'Column 2':'col'})).reset_index(drop=True)

df
Out[127]: 
  Column 1 Column 2 Column 3  col
0        A        E        I    A
1        B        F        J    B
2        C        G        K    C
3        D        H        L    D
4      NaN      NaN      NaN  NaN
5      NaN      NaN      NaN    E
6      NaN      NaN      NaN    F
7      NaN      NaN      NaN    G
8      NaN      NaN      NaN    H
BENY
  • 317,841
  • 20
  • 164
  • 234
1

We need to create a Series of two columns and then use right join to add the column along with extra values into the dataframe.

Use right join as follows:

import pandas as pd

df = pd.DataFrame({'Column 1':['A', 'B', 'C', 'D'],'Column 2':['E', 'F', 'G', 'H'],'Column 3':['I', 'J', 'K', 'L']})
col=df['Column 1'].append(Series(np.nan)).append(df['Column 2']).reset_index(drop=True)
col.name='col'
df = df.join(col, how='right')
print(df)
Pbd
  • 1,219
  • 1
  • 15
  • 32