Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining pandas dataframes by column names

I have two DataFrames with the following column names:

frame_1: event_id, date, time, county_ID  frame_2: countyid, state 

I would like to get a DataFrame with the following columns by joining (left) on county_ID = countyid:

joined_dataframe event_id, date, time, county, state 

I cannot figure out how to do it if the columns on which I want to join are not the index.

like image 925
Alexis Eggermont Avatar asked Dec 04 '13 12:12

Alexis Eggermont


People also ask

How can I join two DataFrames in pandas with different column names?

It is possible to join the different columns is using concat() method. DataFrame: It is dataframe name. axis: 0 refers to the row axis and1 refers the column axis. join: Type of join.

How do I join multiple DataFrames in pandas?

We can use either pandas. merge() or DataFrame. merge() to merge multiple Dataframes. Merging multiple Dataframes is similar to SQL join and supports different types of join inner , left , right , outer , cross .

How do I join multiple columns in pandas?

To merge two pandas DataFrames on multiple columns use pandas. merge() method. merge() is considered more versatile and flexible and we also have the same method in DataFrame.


1 Answers

You can use the left_on and right_on options of pd.merge as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid') 

Or equivalently with DataFrame.merge:

frame_1.merge(frame_2, left_on='county_ID', right_on='countyid') 

I was not sure from the question if you only wanted to merge if the key was in the left hand DataFrame. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid') 

Or

frame_1.merge(frame_2, how='left', left_on='county_ID', right_on='countyid') 
like image 64
Woody Pride Avatar answered Sep 27 '22 21:09

Woody Pride