I am trying to calculate ratio of values for every sub category in a dataframe which has two levels of index

Using python 3 and pandas

arrays = [np.array(['numerator', 'numerator', 'denominator', 'denominator']),
         np.array(['A', 'B', 'A', 'B' ])]

df = pd.DataFrame(np.random.randn(10, 4), index=[n for n in range(10)], columns=arrays)

    numerator                   denominator
        A           B           A           B
0   0.021060    0.150265    -0.798771   0.676246
1   0.490758    -0.310325   -1.632090   -1.246260

Want to add another index 'Ratio' which will have the same two levels [A and B] and will have the ratio as the value. i.e.

['Ratio']['A'] = ['numerator']['A']/['denominator']['A']

['Ratio']['B'] = ['numerator']['B']/['denominator']['B']

Want to do this with a clean code since i need to do this with cases where I can have more levels in the second index i.e. A, B, C, D...

0 Answers