Husy Husy - 4 months ago 17
Python Question

How two merge two dataframes without any index being based

Suppose I have two dataframes X and Y:

import pandas as pd
X = pd.DataFrame({'A':[1,4,7],'B':[2,5,8],'C':[3,6,9]})
Y = pd.DataFrame({'D':[1],'E':[11]})


In [4]: X
Out[4]:
A B C
0 1 2 3
1 4 5 6
2 7 8 9
In [6]: Y
Out[6]:
D E
0 1 11


and then, I want to get the following result dataframe:

A B C D E
0 1 2 3 1 11
1 4 5 6 1 11
2 7 8 9 1 11


how?

Answer Source

Assuming that Y contains only one row:

In [9]: X.assign(**Y.to_dict('r')[0])
Out[9]:
   A  B  C  D   E
0  1  2  3  1  11
1  4  5  6  1  11
2  7  8  9  1  11

or a much nicer alternative from @piRSquared:

In [27]: X.assign(**Y.iloc[0])
Out[27]:
   A  B  C  D   E
0  1  2  3  1  11
1  4  5  6  1  11
2  7  8  9  1  11

Helper dict:

In [10]: Y.to_dict('r')[0]
Out[10]: {'D': 1, 'E': 11}