我正在处理的数据如下:
Name RefSecondary RefMain
test 2 3
bet 3 4
get 1 2
set null 1
net 3 5
我已经完成了一个非常简单的查询,它查找数据框中值的存在并构建层次结构。
sys_role = 'sample.xlsx'
df = pd.read_excel(sys_role,na_filter = False).apply(lambda x: x.astype(str).str.strip())
for i in range(count):
for j in range(count):
if df.iloc[i]['RefMain'] == df.iloc[j]['RefSecondary']:
df.iloc[j, df.columns.get_loc('Name')] = "/".join([df.iloc[i]['Name'],df.iloc[j]['Name']])
j = j+1
i = i+1
我得到的结果如下:
Result RefMain
0 get/test 3
1 test/bet 4
2 set/get 2
3 set 1
4 test/net 5
这个速度真的很慢,而且逻辑也不完美。有没有一种方法可以更快地完成?
逻辑需要如下:
1)Take a value from column RefMain,and find its correspoding RefSecondary value.
2)Look up the RefSecondary value in RefMain,
3)If found Back to Step 1 and repeat.
4)This continues recursively till no value/null is found in RefSecondary column.
生成的数据框应该长成下面这个样子:
Result RefMain
0 set/get/test 3
1 set/get/test/bet 4
2 set/get 2
3 set 1
4 set/get/test/net 5