【发布时间】:2020-05-14 08:35:27
【问题描述】:
给定一个二维数组,我可能在索引 i 处有一行,在索引 j 的另一行中可能有一个或多个数字。我需要从数组中删除那些行 i 和 j 。 同样在任何行中,数字对于该行始终是唯一的。我已经有了没有循环的解决方案,基于 Numpy。 这是我想出的唯一解决方案:
def filter_array(arr):
# Reshape to 1D without hard copy
arr_1d = arr.ravel()
# Make a count of only the existing numbers (faster than histogram)
u_elem, c = np.unique(arr_1d, return_counts=True)
# Get which elements are duplicates.
duplicates = u_elem[c > 1]
# Get the rows where these duplicates belong
dup_idx = np.concatenate([np.where(arr_1d == d)[0] for d in duplicates])
dup_rows = np.unique(dup_idx //9)
# Remove the rows from the array
b = np.delete(arr, dup_rows, axis=0)
return b
这是一个输入数组的(过度简化的)示例:
a = np.array([
[1, 3, 23, 40, 33],
[2, 8, 5, 35, 7],
[9, 32, 4, 6, 3],
[72, 85, 32, 48, 53],
[3, 98, 101, 589, 208],
[343, 3223, 4043, 65, 78]
])
过滤后的数组给出了预期的结果,尽管我没有彻底检查这是否适用于我所有可能的情况:
[[ 2 8 5 35 7]
[ 343 3223 4043 65 78]]
我的典型数组大小约为 10^5 到 10^6 行,固定数量为 9 列。 %timeit 给大约 270 毫秒的时间来过滤每个这样的数组。我有一亿个。在考虑其他方式(例如 GPU)之前,我正在尝试在单个 cpu 上加快速度
这些数据可能已经存在于 Pandas 数据框中。
【问题讨论】:
标签: python arrays numpy duplicates rows