我有一个相当大的np.arraya
(10000-50000个元素,每个坐标(x,y))和另一个更大的np.arrayb
(100000-200000个坐标)。我需要尽快删除a
中不在b
中的元素,只保留b
中存在的a
元素。所有坐标都是整数。例如:
a = np.array([[2,5],[6,3],[4,2],[1,4]])
b = np.array([[2,7],[4,2],[1,5],[6,3]])
期望输出:
a
>> [6,3],[4,2]
对于我提到的大小的阵列,最快的方法是什么
除了Numpy中的解决方案外,我还可以使用任何其他包或导入(例如,转换为基本Pythonlist or set,使用Pandas,等等)的解决方案
这似乎在很大程度上取决于数组大小和“稀疏性”(可能是由于哈希表的魔力)
来自Get intersecting rows across two 2D numpy arrays的答案是
so_8317022
函数外卖似乎(在我的机器上)是:
我机器上的结果是
不确定这是否是最快的方法,但如果将其转换为熊猫索引,则可以使用其交集方法。由于它在后台使用低级c代码,交叉步骤可能非常快,但将其转换为熊猫索引可能需要一些时间
结果是这样的
编辑2:
出于好奇,我对两种方法进行了比较。现在有了更大的索引列表。我将我的第一个索引方法与稍微改进的方法进行了比较,该方法不需要首先创建数据帧,但会立即创建索引,然后再与提出的数据帧合并方法进行比较
这是密码
输出如下所示:
结论:数据帧合并方法(方法2)比在索引上使用交集慢50倍左右。基于多索引(method1)的版本只比method0(我的第一个建议)稍微快一点
EDIT2:@AKX的评论建议:如果您不使用numpy,而是使用纯列表和集合,那么您可以再次获得大约3倍的速度提升。但很明显,您不应该使用合并方法
相关问题 更多 >
编程相关推荐