我对这个简化版本有类似的问题:
实验结果保存在Excel工作表中,我处理完毕 使用Python Pandas的数据并将它们转换为DataFrames。
下面给出两个表格: Table_Race保存在DataFrame中 Table_standard保存在DataFrame std
中>>> data = [["Gold+",1,30,35],["Silver+",1,25,30],["Bronze+",1,20,25],["Gold",2,20,25],["Silver",2,15,20],["Bronze",2,10,15]]
>>> std = pd.DataFrame(data,columns=['Title','League','Start','End'])
>>> std
Title League Start End
0 Gold+ 1 30 35
1 Silver+ 1 25 30
2 Bronze+ 1 20 25
3 Gold 2 20 25
4 Silver 2 15 20
5 Bronze 2 10 15
>>> data = [["John",1,26],["Ryan",1,33],["Mike",1,9],["Jo",2,15],["Riko",2,21],["Kiven",2,13]]
>>> race = pd.DataFrame(data,columns=['Name','League','Distance'])
>>> race
Name League Distance
0 John 1 26
1 Ryan 1 33
2 Mike 1 9
3 Jo 2 21
4 Riko 2 15
5 Kiven 2 13
>>>
我想检查每个玩家的距离并根据标准获得他们的头衔:
Title <= distance in [start, end) and need to match league
例如: 来自联赛2的Jo和15之间的距离[15,20]。请注意,它不是[10,15],因此他获得了冠军&#39; Silver&#39;
预期结果如下:
Name League Distance Title
John 1 26 Silver+
Ryan 1 33 Gold+
Mike 1 9 N/A
Jo 2 21 Gold
Riko 2 15 Silver
Kiven 2 13 Bronze
我可以使用两个循环来实现这一点,它基本上从Table_race获得每个距离并从每一行竞赛中搜索(l,d)(联盟,距离)
寻找条件:
l == League && d >= Start && d < End
但是这个方法是O(N ^ 2)太慢了,因为我的数据很容易超过100,000,这需要几个小时才能完成。
有更好的解决方案吗?
答案 0 :(得分:0)
仍然致力于解决方案,但现在可以开始了:
>>> data = [["Gold+",1,30,35],["Silver+",1,25,30],["Bronze+",1,20,25],["Gold",2,20,25],["Silver",2,15,20],["Bronze",2,10,15]]
>>> std = pd.DataFrame(data,columns=['Title','League','Start','End'])
>>> std
Title League Start End
0 Gold+ 1 30 35
1 Silver+ 1 25 30
2 Bronze+ 1 20 25
3 Gold 2 20 25
4 Silver 2 15 20
5 Bronze 2 10 15
>>> data = [["John",1,26],["Ryan",1,33],["Mike",1,9],["Jo",2,21],["Riko",2,15],["Kiven",2,13]]
>>> race = pd.DataFrame(data,columns=['Name','League','Distance'])
>>> race
Name League Distance
0 John 1 26
1 Ryan 1 33
2 Mike 1 9
3 Jo 2 21
4 Riko 2 15
5 Kiven 2 13
>>> result=pd.merge(race,std,on='League')
>>> result = result[(result.Distance >= result.Start)&(result.Distance < result.End)][["Name","League","Distance","Title"]]
>>> result
Name League Distance Title
1 John 1 26 Silver+
3 Ryan 1 33 Gold+
9 Jo 2 21 Gold
13 Riko 2 15 Silver
17 Kiven 2 13 Bronze
Merge和Multiple conditions链接了解他们的教程和缺点。