python - Groupby into list for non consecutive values
问题描述
I am trying to group by this dataset
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
into this
1 : [A, B, C]
3: [D, E]
2: [ F; G]
1: [ H, I]
2: [ J,K]
so it has to capture the difference in appearances of the elements and not group all at once.
So far I was able to do the normal groupby, df.groupby("col2")["col1"].apply(list)
but it isn't correct.
解决方案
You need distinguish consecutive values by compare shifted values foe not equal with cumulative sum, last remove second level of MultiIndex
:
s = (df.groupby(["col2", df["col2"].ne(df["col2"].shift()).cumsum()])["col1"]
.agg(list)
.reset_index(level=1, drop=True))
推荐阅读
- c++ - 如何在不破坏其父接口的情况下向对象添加属性?
- android - Google Play 上的 Android Auto 程序为我的申请提供了临时通行证
- android - 如何将 pwa 作为一个部分集成到现有的 android 和 ios 应用程序中?
- javascript - 在Angular中将*ngFor与异步管道一起使用时的无限循环
- batch-file - 使用 CMD 提取多个 zip 文件,无需第三方工具
- .net - 如何测试异步任务方法
- vba - 我正在尝试创建一个简单的用户表单,用于在 Word 中添加和删除文本块
- c++ - WriteFile 需要更多时间才能完成
- angular - 预期数量 预期茉莉花
- dialogflow-es - 模拟期间未找到 GSI 帐户关联