python-3.x - 聚合时获取一个热编码值的比例 - 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)
有没有一种熊猫方式可以实现我想要的输出?
解决方案
按季度重新采样,获取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
推荐阅读
- javascript - 在发送到后端时显示数据
- php - 从 Woocommerce 产品管理列表中删除特定的下拉过滤器
- swift - 如何从自定义位置管理器调用另一个视图控制器类中的 didUpdateLocation?
- python - 加载 JSON 棉花糖 TypeError: unhashable type: 'dict'
- vim - vim 实现如何在最后打印的缓冲区上在屏幕上绘制(打印)?
- python - DynamoDB 批量写入操作超过 20 个属性限制
- multithreading - clojure 核心异步和 servlet 取消部署
- javascript - Firebase 安全规则在 v3 中的作用不同
- google-ads-api - 尝试更改出价策略时出现 Google Ads 错误消息
- scala - org.xerial.snappy.SnappyNative 不能转换为 org.xerial.snappy.SnappyNativeAPI