I would like to create an origin-destination matrix from the following data frame in python:
Origin Destination
1 2
1 3
1 4
2 3
3 4
I expect the following matrix:
1 2 3 4
1 0 1 1 1
2 0 0 1 0
3 0 0 0 1
4 0 0 0 0
I know that it could be done in R using table() function, but I don't know how to do it in python. Many thanks for any help.
You could use
pivot_table
with and aggregate function oflen
to build the matrix:which gives:
But you will only find the origins and destination existing in the original matrix.
If you want a row and a column for every possible endpoint, you will have to first build an empty matrix and then add the above one:
which gives the expected matrix: