如何在熊猫中按一列或另一列分组
我有一个表:
col1 col2
0 1 a
1 2 b
2 2 c
3 3 c
4 4 d
如果col1
或 col2
中的匹配值,我希望排将它们分组在一起。也就是说,我想要这样的事情:
> (
df
.groupby(set('col1', 'col2')) # Made-up syntax
.ngroup())
0 0
1 1
2 1
3 1
4 2
有没有办法用大熊猫来做到这一点?
I have a table like:
col1 col2
0 1 a
1 2 b
2 2 c
3 3 c
4 4 d
I'd like rows to be grouped together if they have a matching value in col1
or col2
. That is, I'd like something like this:
> (
df
.groupby(set('col1', 'col2')) # Made-up syntax
.ngroup())
0 0
1 1
2 1
3 1
4 2
Is there a way to do this with pandas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
仅仅用大熊猫实现这一点并不容易。实际上,当第二组连接两个项目时,可以连接两个遥远的组。
您可以使用图理论对此进行处理。使用两个(或更多)组形成的边缘找到连接的组件。一个python库为
networkx
:output:
graph:
另外使用:
输出:
This is not easy to achieve simply with pandas. Indeed, two far away groups can become connected when two items are connected in the second group.
You can approach this using graph theory. Find the connected components using edges formed by the two (or more) groups. A python library for this is
networkx
:output:
graph:
Alternatively using
from_pandas_edgelist
:Output: