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'])
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
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
you could rename
your dataframe's index and then append
one to the other
df = A.rename('{}_a'.format).append(B.rename('{}_b'.format)).sort_index()
This gives
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
try using pd.concat
A.reset_index(inplace=True)
B.reset_index(inplace=True)
A['index']=A['index']+'_a'
B['index']=B['index']+'_b'
A.set_index("index",inplace=True)
B.set_index("index",inplace=True)
final_df = pd.concat([A,B]).sort_values(['A'],ascending=[True])
final_df.index.name=''
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.