Python:如何将矩阵(数据框)除以向量(数据框)

时间:2018-11-08 04:00:03

标签: python r dataframe matrix matrix-multiplication

我需要将矩阵(mat)除以向量(rowSums)

我的矩阵是一个数据框,如下:

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)

rowSums是:

ct1    1
ct2    3
ct3    1
ct4    1
ct5    2
dtype: int64

我需要对mat / rowSums进行划分,但找不到方法。

我正在尝试从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

1 个答案:

答案 0 :(得分:3)

您可以将divpublic Map<String, String> childKV; public Map<String, Object> allChildren; public getChild() { allChildren = new HashMap<>(); DatabaseReference dbRef = fb.child("inventory"); ValueEventListener listener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { for (DataSnapshot childSnap : snapshot.getChildren() { childKV = new HashMap<>(); childKV.put( childSnap.getKey(),childSnap.getValue() ); allChildren.put(childSnap.getKey(), childKV); } } @Override ... }; dbRef.orderByKey().addListenerForSingleValueEvent(listener); dbRef.removeEventListener(listener); printChildren(allChildren); } public void printChildren(Map<String,Object>) {...} 一起使用:

axis=0