【发布时间】:2017-02-10 18:52:53
【问题描述】:
我正在解决一个问题,我必须对相关项目进行分组并为它们分配一个唯一的 ID。我已经用 python 编写了代码,但它没有返回预期的输出。我需要帮助来完善我的逻辑。代码如下:
data = {}
child_list = []
for index, row in df.iterrows():
parent = row['source']
child = row['target']
#print 'Parent: ', parent
#print 'Child:', child
child_list.append(child)
#print child_list
if parent not in data.keys():
data[parent] = []
if parent != child:
data[parent].append(child)
#print data
op = {}
gid = 0
def recursive(op,x,gid):
if x in data.keys() and data[x] != []:
for x_child in data[x]:
if x_child in data.keys():
op[x_child] = gid
recursive(op,x_child,gid)
else:
op[x] = gid
else:
op[x] = gid
for key in data.keys():
#print "Key: ", key
if key not in child_list:
gid = gid + 1
op[key] = gid
for x in data[key]:
op[x] = gid
recursive(op,x,gid)
related = pd.DataFrame({'items':op.keys(),
'uniq_group_id': op.values()})
mapped.sort_values('items')
以下示例
Input:
source target
a b
b c
c c
c d
d d
e f
a d
h a
i f
Desired Output:
item uniq_group_id
a 1
b 1
c 1
d 1
h 1
e 2
f 2
i 2
我的代码在下面给出了错误的输出。
item uniq_group_id
a 3
b 3
c 3
d 3
e 1
f 2
h 3
i 2
另一个例子
Input:
df = pd.DataFrame({'source': ['a','b','c','c','d','e','a','h','i','a'],
'target':['b','c','c','d','d','f','d','a','f','a']})
Desired Output:
item uniq_group_id
a 1
b 1
c 1
d 1
e 2
f 2
My code Output:
item uniq_group_id
e 1
f 1
行的顺序或组 ID 无关紧要。这里重要的是为相关项目分配相同的唯一标识符。整个问题是找到相关的项目组并为它们分配一个唯一的组 ID。
【问题讨论】:
标签: python