![](/img/trans.png)
[英]Pandas Custom Cumulative Calculation Over Group By in DataFrame
[英]Cumulative percentage calculation in a group by dataframe python
分組數據集:
Col-a col-b
24567a 2
3
4
6
56789c 1
2
3
是現有組-by dataframe。 誰能告訴我如何獲得以下格式的 output:
Col-a col-b Cum-Percentage
24567a 2 25%
3 50%
4 75%
6 100%
56789b 1 33.33%
2 66.66%
3 100%
其中每個實例表示為一個組中發生的總實例的一小部分 - 按 dataframe(Pandas,python 3.8)。如果上面不清楚,請參見下圖中的表格。 任何幫助都會很棒,在此先感謝::)在此處輸入圖像描述
假設 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%
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.