Say we have two 2-dimensional arrays, array1 and array2, or alternatively their panda.DataFrame equivalent. For some of the rows in array1, there can be only one or no row in array2 that has equal values in column 2,3, and 4, which I want to extract. That is:
array1 = array([[1,4, 5, 656, 1385, 434],
[11,46, 3, 7356, 585, 74],
[12,45, 5, 656, 135, 134],
[112,475, 3, 356, 285, 134],
])
array2 = array([[15,44, 5, 656, 1385, 434],
[151,436, 3, 356, 285, 74],
[521,406, 5, 656, 135, 24],
[152,445, 54, 56, 635, 134],
[72,727, 12, 16, 55, 634]])
and what I am looking for is:
array1_filtered = array([[1,4, 5, 656, 1385, 434],
[112,475, 3, 356, 285, 134],
[12,45, 5, 656, 135, 134],
])
array2_filtered = array([[15, 44, 5, 656, 1385, 434],
[151, 436, 3, 356, 285, 74],
[521, 406, 5, 656, 135, 24]
])
where both filtered arrays match in terms of their column 2,3, and 4. Even better, have the same matching order in their filtered results like above.
I can think of the following solution but turns out to be quite slow:
array1_filtered = []
array2_filtered = []
for row in array1:
idx = np.where((array2[:, target_columns] == np.array([row[target_columns]])).all(axis=1))[0]
if idx.size != 0:
array1_filtered.append(row.tolist())
array2_filtered.append(array2[idx,:][0].tolist())
array1_filtered = np.asarray(array1_filtered)
array2_filtered = np.asarray(array2_filtered)
Does anyone know a quicker way using numpy or pandas.DataFrame?