2

假设我有以下数据集

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]

我知道如何用groupbyand获得累积总和cumsum,但是例如,单元 1 没有缺失类别 4 的值。

谢谢你的时间!

4

1 回答 1

3
import pandas as pd


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)    

cumsum_count = df.groupby(level=0).apply(lambda x: pd.Series(x['count'].cumsum().values, index=x['cat']))
# unit  cat
# 1     1       8
#       2      11
#       3      13
# 2     1       2
#       2      10
#       4      17
# dtype: int64

cumsum_count = cumsum_count.unstack(level=1).fillna(method='ffill', axis=1)
# cat   1   2   3   4
# unit               
# 1     8  11  13  13
# 2     2  10  10  17

totals = df.groupby(level=0)['count'].sum()
# unit
# 1       13
# 2       17
# Name: count, dtype: int64

cumsum_dist = cumsum_count.div(totals, axis=0)
print(cumsum_dist)

产量

cat          1         2         3  4
unit                                 
1     0.615385  0.846154  1.000000  1
2     0.117647  0.588235  0.588235  1

我真的不知道如何解释这个解决方案——可能是因为我有点意外地到达了它。灵感来自Jeff 的解决方案,它使用

s.apply(lambda x: pd.Series(1, index=x))

将值与索引相关联。一旦您将累积计数()(例如 [8,11,13])与cat数字(索引)(例如 [1,2,3])相关联,您基本上就没有家了。其余的只是unstackfillnadivgroupby的标准应用程序。

于 2013-10-07T21:56:17.840 回答