假设我有以下数据集
df_dict = ({'unit' : [1, 1, 1, 2, 2, 2], 'cat' : [1, 2, 3, 1, 2, 4],
'count' : [8, 3, 2, 2, 8, 7] })
df = pd.DataFrame(df_dict)
df.set_index('unit', inplace = True)
它看起来像这样:
cat count
unit
1 1 8
1 2 3
1 3 2
2 1 2
2 2 8
2 4 7
计数给出了在一个单元中观察到的不同类别的频率。我想得到的是每个单元四个类别的累积频率。请注意,单元1中缺少类别4,单元2中缺少类别3。
因此,最终结果将是
对于单元1:
[8/13, 11/13, 13/13, 13/13]
对于单元2:
[2/17, 10/17, 10/17, 17/17]
我知道如何得到groupby
和cumsum
的累积和,但是例如,单元1没有缺失类别4的值。
谢谢你的时间!
1条答案
按热度按时间s4n0splo1#
产量
我真的不知道如何解释这个解决方案--可能是因为我是偶然得到这个解决方案的。
将值与索引相关联。一旦您将累积计数(values),例如[8,11,13]与
cat
数字(index),例如[1,2,3]相关联,您基本上就可以自由了。其余的只是unstack,fillna,div和groupby的标准应用程序。