python:如何将矩阵(数据帧)除以向量(数据帧)
我需要将矩阵(mat)除以向量(行和) 我的矩阵是一个数据帧,如下所示:python:如何将矩阵(数据帧)除以向量(数据帧),python,r,dataframe,matrix,matrix-multiplication,Python,R,Dataframe,Matrix,Matrix Multiplication,我需要将矩阵(mat)除以向量(行和) 我的矩阵是一个数据帧,如下所示: 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']) 向量是: rowSums = ma
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'])
向量是:
rowSums = mat.sum(axis=1)
行和为:
ct1 1
ct2 3
ct3 1
ct4 1
ct5 2
dtype: int64
我需要把垫子/积木分开,但我找不到路
我正在尝试从R复制此命令:
b = (mat / rowSums(mat))
我需要得到以下结果:
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
您可以与轴=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
您可以与轴=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
它起作用了。。。。一个问题。现在我需要将它从R转换为python。你能给我一些指导吗?:如果我没弄错的话:
mat.div(rowSums,axis=0)。T.div((mat.sum()/mat.values.sum()),axis=0)。T
。测试,它给出了同样的结果它工作。。。。一个问题。现在我需要将它从R转换为python。你能给我一些指导吗?:如果我没弄错的话:mat.div(rowSums,axis=0)。T.div((mat.sum()/mat.values.sum()),axis=0)。T
。在测试中,它给出了相同的结果