I know that in order to add an element to a set it must be hashable, and numpy arrays seemingly are not. This is causing me some problems because I have the following bit of code:
fill_set = set()
for i in list_of_np_1D:
vecs = i + np_2D
for j in range(N):
tup = tuple(vecs[j,:])
fill_set.add(tup)
# list_of_np_1D is a list of 1D numpy arrays
# np_2D is a 2D numpy array
# np_2D could also be converted to a list of 1D arrays if it helped.
I need to get this running faster and nearly 50% of the run-time is spent converting slices of the 2D numpy array to tuples so they can be added to the set.
so I've been trying to find out the following
- Is there any way to make numpy arrays, or something that functions like numpy arrays (has vector addition) hashable so they can be added to sets?
- If not, is there a way I can speed up the process of making the tuple conversion?
Thanks for any help!
a == bdoesn't produce a boolean representing whetheraequalsbif either ofaorbis an array, andsethas no idea what to do with an array of elementwise comparison results or how to callnp.array_equal.numpy.lib.arraysetops)..difference_updateoperation that sets have.tuple(vecs[j,:].tolist())to reduce the convert time. You can even convert the array to a bytes object byvecs[j, :].tobytes()if you only want to save the array in a set.