我对标准化分组数据框中的计数有疑问。
我的数据如下所示:
import pandas as pd
data = [{'system': 'S1', 'id': '1', 'output': ['apple', 'pear']},
{'system': 'S1', 'id': '2', 'output': []},
{'system': 'S1', 'id': '3', 'output': []},
{'system': 'S2', 'id': '4', 'output': ['apple', 'grape']},
{'system': 'S2', 'id': '5', 'output': ['apple']}]
df = pd.DataFrame(data)
表格格式如下:
system id output
0 S1 1 [apple, pear]
1 S1 2 []
2 S1 3 []
3 S2 4 [apple, grape]
4 S2 5 [apple]
如何获得每个系统每个输出的标准化计数?
它看起来应该像这样:
system output perc
S1 apple 0.33
S1 pear 0.33
S2 apple 1.0
S2 grape 0.5
表示apple
和pear
出现在所有S1
输出的三分之一中,apple
出现在所有S2
输出中,grape
出现在所有输出的一半中S2
。
我试图爆炸每个系统的输出并获得每个系统ID的单独计数,但合并它们会丢失该output
列:
outputs = df.explode('output').groupby(['system', 'output']).count()
counts = df.groupby('system').agg('count').id
pd.merge(outputs, counts, on="system")
对于0.25+的熊猫,我们可以使用explode
:
(df.explode('output')
.groupby('system')
.apply(lambda x:x['output'].value_counts()/x['id'].nunique())
.reset_index()
)
输出:
system level_1 output
0 S1 pear 0.333333
1 S1 apple 0.333333
2 S2 apple 1.000000
3 S2 grape 0.500000
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句