gpt4 book ai didi

python - 按列值组合分组

转载 作者:行者123 更新时间:2023-12-04 15:15:15 27 4
gpt4 key购买 nike

我有这样一个数据框

+---+---+---
| A| B|
+---+---+
| 1| 3|
| 1| 1|
| 1| 2|
| 1| 5|
| 2| 5|
| 2| 2|
| 2| 1|
| 3| 1|
| 3| 2|
| 3| 5|
| 4| 3|
| 4| 4|
| 5| 4|
| 5| 3|
| 6| 2|
| 6| 5|
| 6| 1|
| 6| 3|
| 7| 5|
| 7| 4|
| 7| 3|

+---+---+

我想计算每个 A 的两个 B 值的出现次数,以获得 B 的两个值的最常见组合,(顺序无关紧要)我希望结果是:[1,2]、[1,5]、[1,2] 和 [3,4] 作为 B 出现最多的值(我的意思是同一个)我试过这个:

oc=pd.DataFrame(columns=['A','B_combination'])
oc['B_combination']=df.astype('str').groupby('A')['B'].agg([ ';'.join,lambda x: set(x.tolist())])['<lambda_0>'].values
oc['A']=df.astype('str').groupby('A')['B'].agg([ ';'.join,lambda x: set(x.tolist())])['<lambda_0>'].index

得到这样的不同组合:

|A |B_combination|
---+--------------
|1 |{2, 1, 3, 5} |
|2 |{2, 1, 5} |
|3 |{2, 1, 5} |
|4 |{4, 3} |
|5 |{4, 3} |
|6 |{2, 1, 3, 5} |
|7 |{4, 3, 5} |

但是当我申请的时候

oc.groupby('B_combination').count()

为了获得最常见的组合,它不起作用,因为它是一个我试图转换为列表但同样它不起作用的集合

最佳答案

让我们用 groupby() 试试 itertools.combinations:

(df.groupby('A')['B']
.apply(lambda x: pd.Series([tuple(sorted(x)) for x in combinations(x,2)]).value_counts())
.reset_index()
)

输出:

    A level_1  B
0 1 (3, 5) 1
1 1 (2, 5) 1
2 1 (3, 1) 1
3 1 (3, 2) 1
4 1 (1, 5) 1
5 1 (1, 2) 1
6 2 (2, 1) 1
7 2 (5, 1) 1
8 2 (5, 2) 1
9 3 (2, 5) 1
10 3 (1, 5) 1
11 3 (1, 2) 1
12 4 (3, 4) 1
13 5 (4, 3) 1
14 6 (5, 3) 1
15 6 (2, 1) 1
16 6 (2, 3) 1
17 6 (1, 3) 1
18 6 (2, 5) 1
19 6 (5, 1) 1
20 7 (5, 3) 1
21 7 (5, 4) 1
22 7 (4, 3) 1

关于python - 按列值组合分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64448157/

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