Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy: Check if field exists

Tags:

numpy

I have a structured numpy array:

>>> import numpy
>>> a = numpy.zeros(1, dtype = [('field0', 'i2'), ('field1', 'f4')])

Then I start to retrieve some values. However, I do not know in advance, if my array contains a certain field. Therefore, if I try to reach a non-existing field, I am expectedly getting IndexError:

>>> a[0]['field0']
0
>>> a[0]['field2']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index

I could of course go with try-except; however, this can potentially mask some errors, as IndexError does not specify, on which level I hit the non-existing index:

>>> try:
...     a[9999]['field2']['subfield3']
... except IndexError:
...     print('Some index does not exist')
... 
Some index does not exist

I also tried to approach numpy arrays as lists, but this does not work:

>>> if 'field0' in a[0]:
...     print('yes')
... else:
...     print('no')
... 
no

Therefore, question: Is there a way to check if a given field exists in a structured numpy array?

like image 808
Roman Avatar asked Mar 01 '26 03:03

Roman


1 Answers

You could check .dtype.names or .dtype.fields:

>>> a.dtype.names
('field0', 'field1')
>>> 'field0' in a.dtype.names
True
>>> a.dtype.fields
mappingproxy({'field0': (dtype('int16'), 0), 'field1': (dtype('float32'), 2)})
>>> 'field0' in a.dtype.fields
True
like image 88
DSM Avatar answered Mar 05 '26 14:03

DSM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!