Reputation: 490
I have a dictionary with a coordinates entry as an ndarray of tuples,
import numpy as np
data = np.arange(0, 18)
coord = [(i, i, i) for i in data]
arr = np.empty(18, dtype=object)
arr[:] = coord
arr = arr.reshape(3, 6)
d = dict()
d.update({'coord': arr})
I'd like to query the dictionary with a coordinate and be returned it's index within the array.
When I try to find the index with np.where
it returns no match.
np.where(d['coord'] == (0, 0, 0))
(array([], dtype=int64),)
This would ideally return the index (0, 0)
.
When providing an index to the dictionary entry and tuple values it returns True
, so the tuple exists at an index.
d['coord'][0,0] == (0, 0, 0)
True
Can I get the index this way??
Thanks.
Upvotes: 2
Views: 428
Reputation: 231385
The problem is with the ==
test of an object array with a tuple.
In [346]: d['coord']
Out[346]:
array([[(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5)],
[(6, 6, 6), (7, 7, 7), (8, 8, 8), (9, 9, 9), (10, 10, 10),
(11, 11, 11)],
[(12, 12, 12), (13, 13, 13), (14, 14, 14), (15, 15, 15),
(16, 16, 16), (17, 17, 17)]], dtype=object)
In [347]: d['coord']==(0, 0, 0)
/usr/local/bin/ipython3:1: DeprecationWarning: elementwise == comparison failed; this will raise an error in the future.
#!/usr/bin/python3
Out[347]: False
The solution is to compare one object array with another object array:
In [348]: x=np.array(None); x[()]=(0,0,0)
In [349]: x
Out[349]: array((0, 0, 0), dtype=object)
In [350]: d['coord']==x
Out[350]:
array([[ True, False, False, False, False, False],
[False, False, False, False, False, False],
[False, False, False, False, False, False]])
Upvotes: 2