我需要根据B从A中提取一个值,但是使用for循环对于大型数据集来说是不切实际的.虽然下面的代码避免使用for循环,但它仍然需要相同的时间.
import numpy as np
# Given matrices A and B
A = np.array([[254, 0, 0],
[109, 0, 1],
[126, 0, 2],
[66, 0, 3],
[220, 1, 0],
[98, 1, 1],
[230, 1, 2],
[17, 1, 3],
[83, 2, 0],
[106, 2, 1],
[123, 2, 2],
[57, 2, 3]])
B = np.array([[1, 2],
[0, 1],
[1, 0],
[1, 1],
[-1, 2],
[1, 3],
[1, 1],
[0, 0],
[2, 2],
[1, 0],
[2, 3],
[0, 1]])
## these two functions give the same results.
def get_pixel2d(A, B):
corresponding_rows = np.all(A[:, 1:3] == B[:, None], axis=-1)
get_pixel_final = (corresponding_rows * A[:, 0]).sum(axis=1)
return get_pixel_final
# this is more faster
def get_pixel2d(A, B):
corresponding_rows = np.all(A[:, 1:3] == B[:, None], axis=-1)
get_pixel_final = np.sum(A[:, 0] * corresponding_rows, axis=1)
return get_pixel_final
result = get_pixel2d(A, B)
print(result)
[230 109 220 98 0 17 98 254 123 220 57 109]