14
$\begingroup$

I have two data frames df1 and df2 and I would like to merge them into a single data frame. It is as if df1 and df2 were created by splitting a single data frame down the center vertically, like tearing a piece of paper that contains a list in half so that half the columns go on one paper and half the columns go on the other. I would like to merge them back together. How do I do it?

$\endgroup$

3 Answers 3

7
$\begingroup$

Pandas has a built-in merge function. Please refer to the documentation

End-result should be something like this:
df_merged = pd.merge(df1, df2, left_on=['name_indexcolumn_df1_here'],
              right_on=['name_indexcolumn_df2_here'],
              how='inner')
$\endgroup$
4
$\begingroup$

If you split the DataFrame "vertically" then you have two DataFrames that with the same index.

You can use the merge function or the concat function.

With concat with would be something like this:

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

With merge with would be something like this:

pandas.Dataframe.merge([df1,df2], left_index=True)

For more complex merging options see the Merge, join and concat pandas tutorial.

$\endgroup$
1
  • 1
    $\begingroup$ merge is wrong... have you tried running the code? $\endgroup$ Aug 18, 2017 at 11:57
1
$\begingroup$

Considering the dataframes:

Preco2018 with size (8784, 5)

DataFrame 1

Preco 2019 with size (8760, 5)

DataFrame 2

That have the same column names.

You can combine them using pandas.concat, by simply

import pandas as pd

frames = [Preco2018, Preco2019]

df_merged = pd.concat(frames)

Which results in a DataFrame with the following size (17544, 5)

DataFrame result of the combination of two dataframes

If you want to visualize, it ends up working like this

How concat works

(Image Source)

$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.