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):
JavaScript
x
20
20
1
# Create series
2
average_read_intervals = pd.Series([10,20,30,40],
3
index=['a','b','c','d'])
4
region_lengths = pd.Series([100,200,300,400,500,1000],
5
index=['z','y','x','w','v','u'])
6
7
# Convert to dataframes
8
R = pd.DataFrame(region_lengths)
9
A = pd.DataFrame(average_read_intervals)
10
11
# Dot multiplication
12
R.dot(A.T)
13
a b c d
14
z 1000 2000 3000 4000
15
y 2000 4000 6000 8000
16
x 3000 6000 9000 12000
17
w 4000 8000 12000 16000
18
v 5000 10000 15000 20000
19
u 10000 20000 30000 40000
20
I’ve tried the div method, but this just fills the dataframe with NaNs:
JavaScript
1
11
11
1
In [17]: R.div(A.T)
2
Out[17]:
3
0 a b c d
4
0 NaN NaN NaN NaN NaN
5
u NaN NaN NaN NaN NaN
6
v NaN NaN NaN NaN NaN
7
w NaN NaN NaN NaN NaN
8
x NaN NaN NaN NaN NaN
9
y NaN NaN NaN NaN NaN
10
z NaN NaN NaN NaN NaN
11
Likewise the standard division operator also returns the same result:
JavaScript
1
11
11
1
In [18]: R / A.T
2
Out[1]:
3
0 a b c d
4
0 NaN NaN NaN NaN NaN
5
u NaN NaN NaN NaN NaN
6
v NaN NaN NaN NaN NaN
7
w NaN NaN NaN NaN NaN
8
x NaN NaN NaN NaN NaN
9
y NaN NaN NaN NaN NaN
10
z NaN NaN NaN NaN NaN
11
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:
JavaScript
1
2
1
matrix_div = pd.DataFrame(R.values/A.T.values, index=R.index, columns=A.index)
2
which produces the desired matrix of
JavaScript
1
8
1
a b c d
2
z 10 5 3.333333 2.5
3
y 20 10 6.666667 5.0
4
x 30 15 10.000000 7.5
5
w 40 20 13.333333 10.0
6
v 50 25 16.666667 12.5
7
u 100 50 33.333333 25.0
8