Search code examples
pythonpandasdataframematrixpandas-datareader

Can a matrix be formed from dataframe containing two columns and getting the values by dividing the two ,using python?


i have a dataset, which looks like:

 Index   A    B     C
 
   T-1    4    2     2
   T-2   18    3     6  
   T-3   24    4     6
   T-4   49    7     7

Here C is formed by multiplying A/B am trying to create a matrix, that can give take the index both sides and gives me the output:

Desired Output

 A   T-1  T-2    T-3   T-4
 B
T-1  2   1.33    0     0.57
T-2  9    6      4.5    2.57
T-3  12   8      6      4
T-4  24.5 16.33  12.25  7

Basically what it does is just dividing the two A/B and getting the value, i am just lost, can anyone please help?


Solution

  • You can do

    out = df[['A']].dot(df[['B']].rdiv(1).T.values)
    

    .rdiv(1) is to get the reciprocal of values,

    print(out)
    
            0          1      2         3
    T-1   2.0   1.333333   1.00  0.571429
    T-2   9.0   6.000000   4.50  2.571429
    T-3  12.0   8.000000   6.00  3.428571
    T-4  24.5  16.333333  12.25  7.000000