Planck
Planck

Reputation: 1

Pandas concat 2 dataframes combining each row

I am struggled with this.

I have:

import pandas as pd

df1 = pd.Series([0, 1, 2, 3])
df2= pd.Series(["A", "B", "C", "D"])

df3 = pd.concat([df1, df2], axis=0)

my result is:

0
1
2
3 
A
B
C
D

and I need the following output:

0
A
1
B 
2
C
3
D

Upvotes: 0

Views: 298

Answers (2)

BENY
BENY

Reputation: 323226

By using np.insert

   pd.Series(np.insert(df1.astype(str).values,np.arange(len(df1))+1,df2.values))

Out[1105]: 
0    0
1    A
2    1
3    B
4    2
5    C
6    3
7    D
dtype: object

Upvotes: 1

jezrael
jezrael

Reputation: 862481

Add sort_index with reset_index for avoid duplicated index values:

df3 = pd.concat([df1, df2], axis=0).sort_index().reset_index(drop=True)
print (df3)
0    0
1    A
2    1
3    B
4    2
5    C
6    3
7    D
dtype: object

Upvotes: 1

Related Questions