首页 > 解决方案 > 聚合时获取一个热编码值的比例 - Pandas

问题描述

我有一个这样的df,

    Date        Value

0   2019-03-01  0
1   2019-04-01  1
2   2019-09-01  0
3   2019-10-01  1
4   2019-12-01  0
5   2019-12-20  0
6   2019-12-20  0
7   2020-01-01  0

现在,我需要按季度对它们进行分组并获得 1 和 0 的比例。所以,我得到了这样的最终输出,

  Date          Value1 Value0

0 2019-03-31    0      1     
1 2019-06-30    1      0
2 2019-09-30    0      1
3 2019-12-31    0.25   0.75
4 2020-03-31    0      1

我尝试了以下代码,似乎不起作用。

def custom_resampler(array):
    import numpy as np

    return array/np.sum(array)

>>df.set_index('Date').resample('Q')['Value'].apply(custom_resampler)

有没有一种熊猫方式可以实现我想要的输出?

标签: python-3.xpandasaggregate

解决方案


按季度重新采样,获取value_counts并取消堆栈。接下来,使用列的 name 属性重命名列。最后,每一行的值除以每行的总数:

df = pd.read_clipboard(sep='\s{2,}', parse_dates = ['Date'])


res = (df
       .resample(rule="Q",on="Date")
       .Value
       .value_counts()
       .unstack("Value",fill_value=0)
      )


res.columns = [f"{res.columns.name}{ent}" for ent in res.columns]

res = res.div(res.sum(axis=1),axis=0)
res


          Value0   Value1
Date        
2019-03-31  1.00    0.00
2019-06-30  0.00    1.00
2019-09-30  1.00    0.00
2019-12-31  0.75    0.25
2020-03-31  1.00    0.00

推荐阅读