Python:计算两列内值的组合,并找出每个组合的最大频率

Python: Count combinations of values within two columns and find max frequency of each combination

我的 pandas 数据框如下所示:

+-----+---------+-------+
| No. | Section | Group |
+-----+---------+-------+
| 123 |     222 |     1 |
| 234 |     222 |     1 |
| 345 |     222 |     1 |
| 456 |     222 |     3 |
| 567 |     241 |     1 |
| 678 |     241 |     2 |
| 789 |     241 |     2 |
| 890 |     241 |     3 |
+-----+---------+-------+

首先,我需要添加另一列,其中包含 SectionGroup 的每个组合的频率。保留所有行很重要。

期望的输出:

+-----+---------+-------+-------+
| No. | Section | Group | Count |
+-----+---------+-------+-------+
| 123 |     222 |     1 |     3 |
| 234 |     222 |     1 |     3 |
| 345 |     222 |     1 |     3 |
| 456 |     222 |     3 |     1 |
| 567 |     241 |     1 |     1 |
| 678 |     241 |     2 |     2 |
| 789 |     241 |     2 |     2 |
| 890 |     241 |     3 |     1 |
+-----+---------+-------+-------+

第二步是标记 Count 中每个 Section 的最大值。例如,使用这样的 True/False 列:

+-----+---------+-------+-------+-------+
| No. | Section | Group | Count |  Max  |
+-----+---------+-------+-------+-------+
| 123 |     222 |     1 |     3 | True  |
| 234 |     222 |     1 |     3 | True  |
| 345 |     222 |     1 |     3 | True  |
| 456 |     222 |     3 |     1 | False |
| 567 |     241 |     1 |     1 | False |
| 678 |     241 |     2 |     2 | True  |
| 789 |     241 |     2 |     2 | True  |
| 890 |     241 |     3 |     1 | False |
+-----+---------+-------+-------+-------+

原始数据框有很多行。这就是为什么我要求一种有效的方法,因为我想不出一个。

非常感谢!

看看transform

df['Count']=df.groupby(['Section','Group'])['Group'].transform('size')
df['Max']=df.groupby(['Section'])['Count'].transform('max')==df['Count']
df
Out[508]: 
    No  Section  Group  Count    Max
0  123      222      1      3   True
1  234      222      1      3   True
2  345      222      1      3   True
3  456      222      3      1  False
4  567      241      1      1  False
5  678      241      2      2   True
6  789      241      2      2   True
7  890      241      3      1  False