I am trying to divide two series of different length to return the matrix product dataframe of them.
I can multiply them using the dot method (from this answer):
# Create series
average_read_intervals = pd.Series([10,20,30,40],
                                   index=['a','b','c','d'])
region_lengths = pd.Series([100,200,300,400,500,1000],
                           index=['z','y','x','w','v','u'])
# Convert to dataframes
R = pd.DataFrame(region_lengths)
A = pd.DataFrame(average_read_intervals)
# Dot multiplication
R.dot(A.T)
       a      b      c      d
z   1000   2000   3000   4000
y   2000   4000   6000   8000
x   3000   6000   9000  12000
w   4000   8000  12000  16000
v   5000  10000  15000  20000
u  10000  20000  30000  40000
I’ve tried the div method, but this just fills the dataframe with NaNs:
In [17]: R.div(A.T)
Out[17]: 
    0   a   b   c   d
0 NaN NaN NaN NaN NaN
u NaN NaN NaN NaN NaN
v NaN NaN NaN NaN NaN
w NaN NaN NaN NaN NaN
x NaN NaN NaN NaN NaN
y NaN NaN NaN NaN NaN
z NaN NaN NaN NaN NaN
Likewise the standard division operator also returns the same result:
In [18]: R / A.T
Out[1]: 
    0   a   b   c   d
0 NaN NaN NaN NaN NaN
u NaN NaN NaN NaN NaN
v NaN NaN NaN NaN NaN
w NaN NaN NaN NaN NaN
x NaN NaN NaN NaN NaN
y NaN NaN NaN NaN NaN
z NaN NaN NaN NaN NaN
So I’m a bit stumped as to what the correct solution is to my problem.
Any help is gratefully appreciated.
Advertisement
Answer
To do an element wise division operation you can divide the values of each data frame like so:
matrix_div = pd.DataFrame(R.values/A.T.values, index=R.index, columns=A.index)
which produces the desired matrix of
a b c d z 10 5 3.333333 2.5 y 20 10 6.666667 5.0 x 30 15 10.000000 7.5 w 40 20 13.333333 10.0 v 50 25 16.666667 12.5 u 100 50 33.333333 25.0