【问题标题】:Cumulative percentage calculation in a group by dataframe python通过数据框python计算组中的累积百分比
【发布时间】:2021-08-21 16:06:03
【问题描述】:

分组数据集:

Col-a   col-b   
24567a   2
         3
         4
         6
56789c   1
         2
         3

是现有的分组数据框。谁能告诉我如何获得以下格式的输出:

Col-a   col-b   Cum-Percentage
24567a   2       25%
         3       50%
         4       75%
         6       100%
56789b   1       33.33%
         2       66.66%
         3       100%

每个实例表示为分组数据帧(Pandas,python 3.8)中出现的总实例的一小部分。如果上面不清楚,请在下图中显示表格。任何帮助都会很棒,在此先感谢! :) enter image description here

【问题讨论】:

  • 在分组对象中为 cumcount 创建一列并获取 cum_count 列中 col-b 的百分比?

标签: python pandas pandas-groupby


【解决方案1】:

假设 Col-a 是索引:使用 groupby cumcount + groupby transform 然后 map 应用格式:

import pandas as pd

df = pd.DataFrame({
    'Col-a': ['24567a', '24567a', '24567a', '24567a', '56789c', '56789c',
              '56789c'],
    'col-b': [2, 3, 4, 6, 1, 2, 3]
}).set_index('Col-a')

g = df.groupby(level=0)
df['cum-percent'] = (
        (g.cumcount() + 1) / g['col-b'].transform('count') * 100
).map('{:.2f}%'.format)
        col-b cum-percent
Col-a                    
24567a      2      25.00%
24567a      3      50.00%
24567a      4      75.00%
24567a      6     100.00%
56789c      1      33.33%
56789c      2      66.67%
56789c      3     100.00%

如果 Col-a 是包含空格而不是值的列,请使用 replace + ffill,然后使用上述 groupby 函数:

import numpy as np
import pandas as pd

df = pd.DataFrame({
    'Col-a': ['24567a', '', '', '', '56789c', '', ''],
    'col-b': [2, 3, 4, 6, 1, 2, 3]
})

df['Col-a'] = df['Col-a'].replace({'': np.nan}).ffill()
g = df.groupby('Col-a')
df['cum-percent'] = (
        (g.cumcount() + 1) / g['col-b'].transform('count') * 100
).map('{:.2f}%'.format)
    Col-a  col-b cum-percent
0  24567a      2      25.00%
1  24567a      3      50.00%
2  24567a      4      75.00%
3  24567a      6     100.00%
4  56789c      1      33.33%
5  56789c      2      66.67%
6  56789c      3     100.00%

【讨论】:

  • @user:15497888(亨利·埃克)。非常感谢兄弟!它就像一个魅力!祝福你,保持安全:)
  • @Sharath 谢谢!快速提问,您是否有理由接受然后不接受答案?
猜你喜欢
  • 2017-03-03
  • 2021-03-08
  • 2021-10-15
  • 1970-01-01
  • 2020-12-23
  • 2019-01-09
  • 1970-01-01
  • 2021-09-23
  • 1970-01-01
相关资源
最近更新 更多