I need to divide a matrix (mat) by a vector (rowSums)
My matrix is a dataframe as:
mat = pd.DataFrame(
data=[
(1,0,0,0),
(1,1,1,0),
(0,0,1,0),
(0,1,0,0),
(1,0,1,0)],
columns=['ind_1','ind_2','ind_3','ind_4'],
index=['ct1','ct2','ct3','ct4','ct5'])
and the vector is:
rowSums = mat.sum(axis=1)
rowSums is:
ct1 1
ct2 3
ct3 1
ct4 1
ct5 2
dtype: int64
I need to divide mat / rowSums but I can't find the way.
I'm trying to replicate this command from R:
b = (mat / rowSums(mat))
And I need to get the following result:
ind_1 ind_2 ind_3 ind_4
[ct1,] 1.0000000 0.0000000 0.0000000 0
[ct2,] 0.3333333 0.3333333 0.3333333 0
[ct3,] 0.0000000 0.0000000 1.0000000 0
[ct4,] 0.0000000 1.0000000 0.0000000 0
[ct5,] 0.5000000 0.0000000 0.5000000 0
You can use div
with axis=0
:
>>> mat.div(rowSums, axis=0)
ind_1 ind_2 ind_3 ind_4
ct1 1.000000 0.000000 0.000000 0.0
ct2 0.333333 0.333333 0.333333 0.0
ct3 0.000000 0.000000 1.000000 0.0
ct4 0.000000 1.000000 0.000000 0.0
ct5 0.500000 0.000000 0.500000 0.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.