This is what I came up with, thinking with Joins.
import pandas as pd
dt = [['BOS', 'SF'], ['SF', 'LA'], ['LA', 'NYC'], ['SF', 'BOS'],
]
df = pd.DataFrame(columns=['Source', 'destination'], data=dt)
df
|
Source |
destination |
| 0 |
BOS |
SF |
| 1 |
SF |
LA |
| 2 |
LA |
NYC |
| 3 |
SF |
BOS |
calculate the matches between destination -> source
left = df.copy()
right = df.copy().set_index("Source")
dest_to_source = left.join(right, on=[left["destination"]],
lsuffix='_original', rsuffix="_matched", how="inner")
# pandas joins do weird things to the column names, so renaming and reordering
dest_to_source.columns = ["Source_matched","Source_original","destination_original","destination_matched"]
dest_to_source = dest_to_source[["Source_original","destination_original","Source_matched","destination_matched"]]
dest_to_source
and this is the result:
|
Source_original |
destination_original |
Source_matched |
destination_matched |
| 0 |
BOS |
SF |
SF |
BOS |
| 1 |
SF |
LA |
LA |
SF |
| 2 |
LA |
NYC |
NYC |
LA |
| 3 |
SF |
BOS |
BOS |
SF |
then you can do the same thing for the source -> destination (for the "vice-versa" part of the question)\
right = df.copy().set_index("destination")
source_to_dest = left.join(right, on=[left["Source"]], lsuffix='_original',rsuffix='_matched', how="inner")
source_to_dest.columns = ["destination_matched","Source_original","destination_original","Source_matched"]
source_to_dest = source_to_dest[["Source_matched","destination_matched","Source_original","destination_original"]]
source_to_dest
|
Source_matched |
destination_matched |
Source_original |
destination_original |
| 0 |
SF |
BOS |
BOS |
SF |
| 1 |
BOS |
SF |
SF |
LA |
| 3 |
BOS |
SF |
SF |
BOS |
| 2 |
SF |
LA |
LA |
NYC |