combine two dataframes in python

There are several ways to combine two dataframes in Python using the Pandas library.

  1. Concatenation: If the two dataframes have the same columns, you can concatenate them vertically or horizontally using the concat() method.

For example, to concatenate two dataframes named df1 and df2 vertically:

main.py
import pandas as pd
result = pd.concat([df1, df2])
51 chars
3 lines

To concatenate them horizontally, set the axis parameter to 1:

main.py
result = pd.concat([df1, df2], axis=1)
39 chars
2 lines
  1. Merge: If the two dataframes have different columns but share a common column, you can merge them using the merge() method.

For example, to merge two dataframes named df1 and df2 on a common column named key:

main.py
result = pd.merge(df1, df2, on='key')
38 chars
2 lines

There are several types of joins you can perform using the how parameter in the merge method, such as inner join, left join, right join, and outer join.

These are some of the methods to combine two dataframes in Python using Pandas library.

gistlibby LogSnag