【发布时间】:2016-01-26 10:25:23
【问题描述】:
我在 Python 3.4 中使用 pandas 来识别两个数据帧之间的匹配。匹配基于严格相等,但最后一列除外,其中紧密匹配 (+/- 5) 很好。
一个数据框包含许多行,在这种情况下,第二个数据框只是一行。如前所述,所需的结果是包含与行匹配的第一个数据帧的子集的数据帧。
我首先采用了布尔索引的具体解决方案,但这需要一段时间才能遍历所有数据,因此我尝试了 pandas 合并功能。但是,在我的测试数据上,我的合并实现甚至更慢。它的运行速度比布尔索引慢 2 到 4 倍。
这是一个测试运行:
import pandas as pd
import random
import time
def make_lsts(lst, num, num_choices):
choices = list(range(0,num_choices))
[lst.append(random.choice(choices)) for i in range(0,num)]
return lst
def old_way(test, data):
t1 = time.time()
tmp = data[(data.col_1 == test.col_1[0]) &
(data.col_2 == test.col_2[0]) &
(data.col_3 == test.col_3[0]) &
(data.col_4 == test.col_4[0]) &
(data.col_5 == test.col_5[0]) &
(data.col_6 == test.col_6[0]) &
(data.col_7 == test.col_7[0]) &
(data.col_8 >= (test.col_8[0]-5)) &
(data.col_8 <= (test.col_8[0]+5))]
t2 = time.time()
print('old time:', t2-t1)
def new_way(test, data):
t1 = time.time()
tmp = pd.merge(test, data, how='inner', sort=False, copy=False,
on=['col_1', 'col_2', 'col_3', 'col_4', 'col_5', 'col_6', 'col_7'])
tmp = tmp[(tmp.col_8_y >= (test.col_8[0] - 5)) & (tmp.col_8_y <= (test.col_8[0] + 5))]
t2 = time.time()
print('new time:', t2-t1)
if __name__ == '__main__':
t1 = time.time()
data = pd.DataFrame({'col_1':make_lsts([], 4000000, 7),
'col_2':make_lsts([], 4000000, 3),
'col_3':make_lsts([], 4000000, 3),
'col_4':make_lsts([], 4000000, 5),
'col_5':make_lsts([], 4000000, 4),
'col_6':make_lsts([], 4000000, 4),
'col_7':make_lsts([], 4000000, 2),
'col_8':make_lsts([], 4000000, 20)})
test = pd.DataFrame({'col_1':[1], 'col_2':[1], 'col_3':[1], 'col_4':[4], 'col_5':[0], 'col_6':[1], 'col_7':[0], 'col_8':[12]})
t2 = time.time()
old_way(test, data)
new_way(test, data)
print('time building data:', t2-t1)
在我最近的运行中,我看到以下内容:
# old time: 0.2209608554840088
# new time: 0.9070699214935303
# time building data: 75.05818915367126
请注意,即使具有合并功能的新方法在处理值范围的最后一列上也使用布尔索引,但我认为合并可能能够解决问题。这显然不是这种情况,因为第一列的合并几乎占用了新方法中使用的所有时间。
是否可以优化我的合并功能实现? (来自 R 和 data.table,我花了 30 分钟寻找在 pandas 数据框中设置键的方法,但未成功。)这只是合并不擅长处理的问题吗?为什么在这个例子中布尔索引比合并更快?
我不完全了解这些方法的内存后端,因此感谢任何见解。
【问题讨论】: