Ниже приведено решение.
places = df["OD"].unique()
places.sort()
od_df = pd.DataFrame(df["OD"].values.reshape((-1, 2)), columns=["O", "D"])
od_matrix = od_df.groupby(["O", "D"]).size().unstack().reindex(index=places, columns=places)
od_matrix.fillna(0, downcast="infer", inplace=True)
Вы также можете использовать pd.pivot_table
и заменить четвертую строку на
od_matrix = pd.pivot_table(od_df, index="O", columns="D", aggfunc="size").reindex(index=places, columns=places)