gpt4 book ai didi

python - 将非连续值分组到列表中

转载 作者:行者123 更新时间:2023-12-02 02:24:18 25 4
gpt4 key购买 nike

我正在尝试按此数据集进行分组

    col1    col2
0 A 1
1 B 1
2 C 1
3 D 3
4 E 3
5 F 2
6 G 2
7 H 1
8 I 1
9 j 2
10 K 2

进入此

1 : [A, B, C]
3: [D, E]
2: [ F; G]
1: [ H, I]
2: [ J,K]

因此它必须捕获元素外观的差异,而不是一次将所有元素分组。

到目前为止,我能够执行正常的 groupby,df.groupby("col2")["col1"].apply(list) 但它不正确。

最佳答案

您需要通过比较不等于累积和的移位值来区分连续值,最后删除MultiIndex的第二级:

s = (df.groupby(["col2", df["col2"].ne(df["col2"].shift()).cumsum()])["col1"]
.agg(list)
.reset_index(level=1, drop=True))

关于python - 将非连续值分组到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65933834/

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