2

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

1
  • If the lengths are the same you can just concat pd.concat([df1,df2], axis=1, ignore_index=True) Commented Oct 15, 2014 at 15:08

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.