如何在python中检查数据组是否连接
假设我们有这样一个数据集:如何在python中检查数据组是否连接,python,pandas,Python,Pandas,假设我们有这样一个数据集: import pandas as pd import numpy as np df = pd.DataFrame({'ID':[1,1,1,2,2,2,3,3,3,4,4,4], 'Number':[234, 43, 455, 112, 45, 234, 982, 41, 112, 46, 109, 4]}) 现在,如果运行上面的代码,您将看到ID的1、2和3都是“已连接”的,即ID 1通过Number==234连接到ID 2,ID 2通过Number==112
import pandas as pd
import numpy as np
df = pd.DataFrame({'ID':[1,1,1,2,2,2,3,3,3,4,4,4], 'Number':[234, 43, 455, 112, 45, 234, 982, 41, 112, 46, 109, 4]})
现在,如果运行上面的代码,您将看到ID的1、2和3都是“已连接”的,即ID 1通过Number==234连接到ID 2,ID 2通过Number==112连接到ID 3。但是ID 4没有连接到其他3个ID。所以我想要一个像这样的df_决赛
df_final = pd.DataFrame({'ID':[1,1,1,2,2,2,3,3,3,4,4,4], 'Number':[234, 43, 455, 112, 45, 234, 982, 41, 112, 46, 109, 4], 'Group':[1,1,1,1,1,1,1,1,1,2,2,2]})
我的数据集很大,所以我需要一些尽可能高效的代码。我定义了一个'is_a_neighbor'函数来检查两个ID之间是否有重叠。如果两个ID连接(即有重叠),则返回“True”。我想我需要以某种方式将它嵌入到一个循环中。下面是函数:
def is_a_neighbor(id_1, id_2):
val = np.isin(df[df['ID'] == id_1][['Number']].to_numpy(), df[df['ID'] == id_2][['Number']].to_numpy()).any()
return val
还有试运行
# Test is_a_neighbor function
id_1 = 1
id_2 = 2
val = is_a_neighbor(id_1, id_2)
val
将返回“True”。感谢您在这方面提供的帮助/指导。以下代码应该可以工作:
将熊猫作为pd导入
将networkx导入为nx
df=pd.DataFrame({'ID':[1,1,1,2,2,2,3,3,4,4],
‘数字’:[234、43、455、112、45、234、982、41、112、46、109、4]})
df.ID=df.ID.astype(str)
g=nx.来自边列表(df,'ID','Number')
连接的_组件=nx。连接的_组件(g)
d={y:i代表i,x在枚举中(连接的_组件)代表y在x}
df['group']=df.ID.replace(d)
df.ID=df.ID.astype(int)
之所以将ID
列转换为字符串,是因为我们希望ID
列中的1
与Number
列中的1
不同
如果我们不这样做,下面的示例将只显示一个组:
身份证件
数
1.
3.
2.
3.
3.
4.
据我所知,有一长串对(Id,Number)和两个不同的Id属于同一个组,如果有任何数字N,那么(i1,N)和(id2,N)都存在 我不知道你为什么认为你需要熊猫或者小矮人来做这个 为什么不这样做呢:
data = [(1, 234), (1, 43), (1, 455), (1, 112), (2, 234), ...]
# Create sets of numbers for each index
number_sets = {}
for (index, number) in data:
# if we've not seen the index before we create an empty set
if index not in number_sets:
number_sets[index] = set()
number_sets[index].add(number)
现在我们创建一个组列表,每个组记录一个索引列表和一组使用这些索引找到的数字
groups = []
for (index, numbers) in number_sets.items():
for (index_list, superset) in groups:
# if any of the numbers are in the superset then this index belongs to this group
if not superset.isdisjoint(numbers):
index_list.append(index)
superset.join(numbers)
break
else:
# We never had a break so we've found a new group
groups.append(([index], numbers))
您是否考虑过使用NetworkX这样的图形专用库?工作起来很有魅力。。谢谢我很乐意帮忙!如果你觉得答案有帮助,请记住接受。是的,比预期快得多!