Search code examples
pythonpandasmatrixcrosstab

Is there a simple way to convert a pandas series to a crosstab of ratios for values in the series?


Input

name    score
bob     2           
fred    4           
jim     1           
anne    5   

Desired Output (ratio of scores: e.g. bob*fred in row 1 = 2/4, etc.)

name    bob fred    jim anne
bob     1   0.5     2   0.4
fred    2   1       4   0.8
jim     0.5 0.2     1   0.2
anne    2.5 1.25    5   1

Solution

  • We can try outer np.divide.outer to compute the outer division of score column

    n, s = df.to_numpy().T
    pd.DataFrame(np.divide.outer(s, s), n, n)
    

          bob  fred  jim anne
    bob   1.0   0.5  2.0  0.4
    fred  2.0   1.0  4.0  0.8
    jim   0.5  0.25  1.0  0.2
    anne  2.5  1.25  5.0  1.0