首页 > 解决方案 > 使用 python pandas 将字符串数据汇总为百分比

问题描述

给定以下数据:

x = "foo"
y = "bar"
z = "baz"
t1 = "fior"
t2 = "ropir"

d1 = pd.DataFrame(dict(type=[t1] * 4 + [t2] * 4, response=[x, y, x, x, x, z, z, z],))

看起来像

    type response
0   fior      foo
1   fior      bar
2   fior      foo
3   fior      foo
4  ropir      foo
5  ropir      baz
6  ropir      baz
7  ropir      baz

怎么能概括为

d2 = pd.DataFrame(
    dict(
        type=[t1] * 3 + [t2] * 3,
        response=[x, y, z] * 2,
        percentage=[0.75, 0.25, 0, 0.25, 0, 0.75],
    )
)

这是作为

    type response  percentage
0   fior      foo        0.75
1   fior      bar        0.25
2   fior      baz        0.00
3  ropir      foo        0.25
4  ropir      bar        0.00
5  ropir      baz        0.75

标签: pythonpandasgroup-by

解决方案


您可以使用groupby和 normalized value_counts,然后rename是 Series ,使用每列中的from值reindex创建所有可能的类型响应,然后 finally 。MultiIndex.from_productuniquereset_index

d1.groupby('type')['response'].value_counts(normalize=True)\
  .rename('percentage')\
  .reindex(pd.MultiIndex.from_product([d1['type'].unique(), d1['response'].unique()],
                                      names=['type','response']), 
           fill_value=0)\
  .reset_index()

    type response  percentage
0   fior      foo        0.75
1   fior      bar        0.25
2   fior      baz        0.00
3  ropir      foo        0.25
4  ropir      bar        0.00
5  ropir      baz        0.75

推荐阅读