【发布时间】:2021-06-20 07:08:25
【问题描述】:
我有一个 pandas 数据框 test,我想将其值转换为 categories 中所有整数的百分位数,例如:
import pandas as pd
categories = [0,1,2,3,4,5,6,7,8,9,10]
test
id value
foo 0
foo 0
foo 1
foo 1
foo 5
foo 4
foo 4
foo 4
foo 3
foo 3
bar 2
bar 2
bar 2
bar 2
bar 2
bar 6
bar 6
bar 6
bar 6
bar 6
我遇到的问题是将 0 百分位数映射到类别中所有可能的整数。我当我尝试
test.groupby('id')['value'].apply(lambda x: x.value_counts(normalize=True)).unstack().fillna(0)
返回以下数据框,但缺少值 7、8、9、10 等,因为它们不包含在每个 id 中:
0 1 2 3 4 5 6
id
bar 0.0 0.0 0.5 0.0 0.0 0.0 0.5
foo 0.2 0.2 0.0 0.2 0.3 0.1 0.0
有没有一种有效的方法将catgories的所有值添加到value_count聚合函数中,从而返回以下结果?
0 1 2 3 4 5 6 7 8 9 10
foo 0.2 0.2 0.0 0.2 0.3 0.1 0.5 0 0 0 0
bar 0.0 0.0 0.5 0.0 0.0 0.0 0.0 0 0 0 0
【问题讨论】:
标签: python pandas group-by pandas-groupby aggregate