gpt4 book ai didi

python - 带有 bool OR 的 Pandas groupby

转载 作者:行者123 更新时间:2023-12-01 01:19:07 25 4
gpt4 key购买 nike

我想根据 pandas 中的 bool 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+

关于python - 带有 bool OR 的 Pandas groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015062/

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