首页 > 解决方案 > 带有布尔值或的 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. 还有更直接的选择吗?

标签: pythonpandaspandas-groupby

解决方案


注意我认为这是网络问题,所以我们这样做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+

推荐阅读