python - 带有布尔值或的 Pandas groupby
问题描述
我想根据熊猫中的布尔 OR 标准生成一组组。组由在 A 列或 B 列上匹配的成员组成。
例如,在这个数据框中:
df = pd.DataFrame([[1,1],[2,2],[2,3],[2,4],[3,3],[4,5]], columns = ['A','B'])
A B
0 1 1
1 2 2
2 2 3
3 2 4
4 3 3
5 4 5
因为第 1、2 和 3 行在 A 列上匹配,2 和 4 在 B 列上匹配,所以我希望 id 值是:
A B id
0 1 1 0
1 2 2 1
2 2 3 1
3 2 4 1
4 3 3 1
5 4 5 2
除了使用连接创建 NxN scipy 图并使用scipy.sparse.csgraph.connected_components
. 还有更直接的选择吗?
解决方案
注意我认为这是网络问题,所以我们这样做networkx
import networkx as nx
G=nx.from_pandas_edgelist(df, 'A', 'B')
l=list(nx.connected_components(G))
l
[{1}, {2, 3}]
from itertools import chain
l=[dict.fromkeys(y,x)for x,y in enumerate(l)]#create the list of dict for later map
d=dict(chain(*map(dict.items,l)))# flatten the list of dict to one dict
df['ID']=df.B.map(d)
df
A B ID
0 1 1 0
1 2 2 1
2 2 3 1
3 3 3 1
更新
s1=df.A.astype('category').cat.codes.sort_values()
s2=df.B.astype('category').cat.codes.sort_values()
s=((s1==s1.shift())|(s2==s2.shift())).eq(False).cumsum()
s
#df['new']=s
Out[25]:
0 1
1 2
2 2
3 2
4 2
5 3
dtype: int32+
推荐阅读
- flutter - 如何在颤动中增加滑块轨道宽度
- java - JPA 批量插入不会提高性能
- r - 是否有用于将表格按两行分组的 R 函数?
- python - 当我们拆分训练和测试时,我们希望将目标变量设为动态
- ionic-framework - 当互联网未连接到设备时本地存储数据
- opencv - OpenCV:如何关闭二进制图像中的边缘
- javascript - 如何无限循环一个函数(而不是使用传统的for循环)
- hadoop - 直线中 Tez 作业的作业名称并在 YARN 中查看
- elasticsearch - 在 ElasticSearch 中为审计编制索引
- spring-integration - 有没有办法使用spring集成将外部服务作为pubsub模型的订阅者