woshitom
woshitom

Reputation: 5131

Python, how to merge 2 pandas DataFrame

Lets say I have two differents pandas Dataframe with different index for example:

df1:

email                |       other_field
_________________________________________
[email protected]     |           2
[email protected]     |           1
[email protected]     |           6

and df2:

new_field
__________
    1
    7
    4

The 2 dataframes have the same size. How can I merge the two of them to have this similar output?

df3:

email                |       other_field     |       new_field
________________________________________________________________
[email protected]     |           2           |           1
[email protected]     |           1           |           7
[email protected]     |           6           |           4

I tried this:

df3 = pd.merge(df1, df2, left_index=True, right_index=True)

but despite df1 and df2 has the same size, df3 has a lower size

Upvotes: 2

Views: 294

Answers (1)

EdChum
EdChum

Reputation: 393893

You can just concat in this case:

In [70]:

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

Out[70]:
              email  other_field  new_field
0  [email protected]            2          1
1  [email protected]            1          7
2  [email protected]            6          4

You could elect to pass ignore_index=True if required.

join would also work:

In [71]:

df1.join(df2)

Out[71]:
              email  other_field  new_field
0  [email protected]            2          1
1  [email protected]            1          7
2  [email protected]            6          4

Also in the case where the indices match, direct assignment would also work:

In [72]:

df1['new_field'] = df2['new_field']
df1
Out[72]:
              email  other_field  new_field
0  [email protected]            2          1
1  [email protected]            1          7
2  [email protected]            6          4

Upvotes: 2

Related Questions