use*_*654 3 python merge pandas
I want to merge 2 DataFrames, such that in the new DataFrame first row = row 1 from df1 and the second row is the first row from df2 etc.
A=pd.DataFrame({'A':[1,3,5], 'B': [7,9,11]}, index = ['bs','ss','db'])
B=pd.DataFrame({'A':[2,4,6], 'B': [8,10,12]}, index = ['bs','ss','db'])
Run Code Online (Sandbox Code Playgroud)
Note that row and column labels are exactly the same and both dataframes have the same dimension.
So the desired output should look like
A B
bs_a 1 7
bs_b 2 8
ss_a 3 9
ss_b 4 10
db_a 5 11
db_b 6 12
Run Code Online (Sandbox Code Playgroud)
Im not familiar with pandas merge, and after looking in the documentation i still dont know how to do this
You can do concat with keys , the merge the multiple index
s=pd.concat([A,B],keys=['a','b']).sort_index(level=1)
s.index=s.index.map('{0[1]}_{0[0]}'.format)
s
Out[225]:
A B
bs_a 1 7
bs_b 2 8
db_a 5 11
db_b 6 12
ss_a 3 9
ss_b 4 10
Run Code Online (Sandbox Code Playgroud)