我正在构建一个网络图,我希望边的权重是跟随某个特定边的输出的百分比。给出以下示例:
import pandas as pd
dff = pd.DataFrame()
dff['source'] = ['a','a','a','b','b','b','b']
dff['target'] = ['b','c','b','d','d','e','d']
我想回到这样的事情:
a b 66%
c 34%
b d 75%
e 25%
到目前为止,我只能分组和总结,不知道如何将其分成百分比?
dff.groupby(['source', 'target']).size()
答案 0 :(得分:2)
你走在正确的轨道上。使用groupby
+ count
-
v = df.groupby(['source', 'target']).source.count()
您也可以使用size
,但请注意size
也计算NaN
个条目(count
没有) -
v = df.groupby(['source', 'target']).size()
现在,找到0 th 指数水平的总和,并将原始金额除以此总和 -
v / v.sum(level=0) * 100
source target
a b 66.666667
c 33.333333
b d 75.000000
e 25.000000
Name: source, dtype: float64
如果您想要百分比右侧的%
符号,请转换为字符串 -
(v / v.sum(level=0) * 100).round(2).astype(str) + '%'
source target
a b 66.67%
c 33.33%
b d 75.0%
e 25.0%
Name: source, dtype: object