Home > Mobile >  Merge two dataframes with special order
Merge two dataframes with special order

Time:05-17

I have two df:

Type   price   stock
a      2       2
a      4       1
a      3       3


Type   price   stock
b      1       1
b      2       4
c      3       2
c      4       1
c      5       3
c      5       3
b      2       4

I would like to merge these two df, the resulting df I would like to get is

Type   price*stock
b      1       1
b      2       4
a      2       2
c      3       2
c      4       1
a      4       1
c      5       3
c      5       3
a      3       3
b      2       4

From top, you could see I would like to insert the first df into the second the df, the logic is two rows from the second df, and then one row from the first df.

How could I achieve it?

CodePudding user response:

You can do

df2.index = df2.index//2
out = df2.append(df1).sort_index()
Out[42]: 
  Type  price  stock
0    b      1      1
0    b      2      4
0    a      2      2
1    c      3      2
1    c      4      1
1    a      4      1
2    c      5      3
2    c      5      3
2    a      3      3
3    b      2      4

CodePudding user response:

This works

# floor divide the index to make df2 blocks of 2
df2['groups'] = df2.index//2
df1['groups'] = df1.index
# concatenat and sort by groups, then drop the groups column
final = pd.concat([df2, df1]).sort_values(by='groups').drop('groups', axis=1)
  Type  price  stock
0    b      1      1
1    b      2      4
0    a      2      2
2    c      3      2
3    c      4      1
1    a      4      1
4    c      5      3
5    c      5      3
2    a      3      3
6    b      2      4
  • Related