gpt4 book ai didi

python - 我如何获得由 Pandas 数据框中的值表示的两个连接代码的聚合百分比

转载 作者:行者123 更新时间:2023-12-03 19:05:58 25 4
gpt4 key购买 nike

我是 Python 新手并试图了解数据操作

df
Alpha AlphaComboCount
12-99 8039
22-99 1792
12-99,138-99 1776
12-45,138-45 1585
21-99 1225
123-99 1145
121-99 1102
21-581 1000
121-99,22-99 909
32-99 814
21-141 75
12-581,12-99 711
347-99 685
2089-281 685
123-49,121-29,22-79 626
121-99,123-99,22-99 4
如上所示,有两列。 Alpha 是由 '-' 分隔的 2 个代码串联而成的字符串。我的目标是通过第一个代码找到 alphacombocount 的总百分比。
例如:
其中有 21 个子代码-
Alpha   AlphaComboCount  Percent
21-99 1225 53%
21-141 75 3.2%
21-581 1000 43.3%
您在上面看到的目标是获得相应的百分比。因为这里的总聚合是 21 个子代码中的 2300 个。
组合代码变得更复杂:
   123-49,121-29,22-79       626  99%
121-99,123-99,22-99 4 0.6%
正如您在上面看到的,所有第一个子代码都相同但重新排列。这也是获取百分比值的有效情况。只要组合与'-'之前的第一个子码相同。我如何才能获得所有 alpha 组合的百分比值?有这个算法吗?

最佳答案

首先,您想将单元格内的代码分开,然后您可以提取第一个代码和 groupby:

# separate the codes
tmp = df.assign(FirstCode=df.Alpha.str.split(','))

# extract the first code
tmp['FirstCode'] = [tuple(sorted(set(x.split('-')[0] for x in cell)))
for cell in tmp.FirstCode]

# sum per each first codes with groupby
sum_per_code = tmp['AlphaComboCount'].groupby(tmp['FirstCode']).transform('sum')

# percentage is just a simple division
tmp['Percent'] = tmp['AlphaComboCount']/sum_per_code

# let's print the output:
print(tmp.sort_values('FirstCode'))
输出:
                  Alpha  AlphaComboCount       FirstCode   Percent
0 12-99 8039 (12,) 0.918743
11 12-581,12-99 711 (12,) 0.081257
2 12-99,138-99 1776 (12, 138) 0.528414
3 12-45,138-45 1585 (12, 138) 0.471586
6 121-99 1102 (121,) 1.000000
14 123-49,121-29,22-79 626 (121, 123, 22) 0.993651
15 121-99,123-99,22-99 4 (121, 123, 22) 0.006349
8 121-99,22-99 909 (121, 22) 1.000000
5 123-99 1145 (123,) 1.000000
13 2089-281 685 (2089,) 1.000000
4 21-99 1225 (21,) 0.532609
7 21-581 1000 (21,) 0.434783
10 21-141 75 (21,) 0.032609
1 22-99 1792 (22,) 1.000000
9 32-99 814 (32,) 1.000000
12 347-99 685 (347,) 1.000000

关于python - 我如何获得由 Pandas 数据框中的值表示的两个连接代码的聚合百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63638948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com