To merge two dataframes based on a column in Python, you can use the merge()
function from the pandas
library.
The syntax for merging dataframes is as follows:
main.py58 chars2 lines
Here, left_df
and right_df
are the dataframes you want to merge and column_name
is the name of the column that you want to merge on.
For example, let's assume you have two dataframes df1
and df2
with a common column called user_id
.
main.py180 chars5 lines
To merge these dataframes on the user_id
column, you can use the following code:
main.py45 chars2 lines
This will give you a merged dataframe with columns user_id
, name
and age
. The output would look like this:
main.py69 chars4 lines
Note that the resulting dataframe only includes the rows where the user_id
column was present in both df1
and df2
. You can specify different types of joins and merge options using additional parameters in the merge()
function.
gistlibby LogSnag