How to merge two DataFrames into single matching the column values
<p>Two DataFrames have matching values stored in their corresponding 'names' and 'flights' columns.
While the first DataFrame stores the distances the other stores the dates:</p>

<pre><code>import pandas as pd   

distances = {'names': ['A', 'B','C'] ,'distances':[100, 200, 300]}
dates = {'flights': ['C', 'B', 'A'] ,'dates':['1/1/16', '1/2/16', '1/3/16']}

distancesDF = pd.DataFrame(distances)
datesDF = pd.DataFrame(dates)
</code></pre>

<p>distancesDF:</p>

<pre><code>   distances    names
0        100        A
1        200        B
2        300        C
</code></pre>

<p>datesDF:</p>

<pre><code>    dates  flights
0  1/1/16        A
1  1/2/16        B
2  1/3/16        C
</code></pre>

<p>I would like to merge them into single Dataframe in a such a way that the matching entities are synced with the corresponding distances and dates. So the resulted DataFame would look like this:</p>

<p>resultDF:</p>

<pre><code>   distances    names     dates 
0        100        A    1/1/16 
1        200        B    1/2/16 
2        300        C    1/3/16
</code></pre>

<p>What would be the way of accomplishing it?</p>

<p>There is nothing that ties these dataframes together other than the positional index.  You can accomplish your desired example output with <code>pd.concat</code></p>

<pre><code>pd.concat([distancesDF, datesDF.dates], axis=1)
</code></pre>

<p><a href="https://i.stack.imgur.com/5YLVN.png" rel="nofollow"><img src="https://i.stack.imgur.com/5YLVN.png" alt="enter image description here"></a></p>

<hr>

<p>To address the edit and @kartik's comment</p>

<p>if we create the dfs to match what's displayed.</p>

<pre><code>distances = {'names': ['A', 'B','C'] ,'distances':[100, 200, 300]}
dates = {'flights': ['A', 'B', 'C'] ,'dates':['1/1/16', '1/2/16', '1/3/16']}

distancesDF = pd.DataFrame(distances)
datesDF = pd.DataFrame(dates)
</code></pre>

<p>then the following two options produce the same and probably desired result.</p>

<p><strong><em>merge</em></strong></p>

<pre><code> distancesDF.merge(datesDF, left_on='names', right_on='flights')[['distances', 'names', 'dates']]
</code></pre>

<p><strong><em>join</em></strong></p>

<pre><code>distancesDF.join(datesDF.set_index('flights'), on='names')
</code></pre>

<p>both produce</p>

<p><a href="https://i.stack.imgur.com/5YLVN.png" rel="nofollow"><img src="https://i.stack.imgur.com/5YLVN.png" alt="enter image description here"></a></p>

python pandas dataframe