大Pandas缺失类的累计和

2024-06-09 17:03:13 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下数据集

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)

看起来像这样:

^{pr2}$

计数给出了在一个单元中观察到的不同类别的频率。 我想得到的是每个单元四个类别的累计频率。注意,1号机组缺少4类机组,2号机组缺少3号机组。在

因此,最终结果将是

对于1号机组:

[8/13, 11/13, 13/13, 13/13]

对于2号机组:

[2/17, 10/17, 10/17, 17/17]

我知道如何用groupbycumsum来获得累计和,但是例如,单元1没有缺少类别4的值。在

谢谢你的时间!在


Tags: 数据dataframedfindexcountunit类别dict
1条回答
网友
1楼 · 发布于 2024-06-09 17:03:13
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)

收益率

^{pr2}$

我真的不知道该如何解释这个解决方案,可能是因为我有点偶然。灵感 来自Jeff's solution,它使用

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

将值与索引相关联。一旦你把累计计数(),例如[8,11,13],与cat个数字(索引)相关联,例如[1,2,3],你就基本上没有家了。剩下的只是unstackfillnadiv和{a5}的标准应用程序。在

相关问题 更多 >