I look up in a table if keys have associated arrays, or not. By design, my table.__getitem__()
somtimes returns None
rather than KeyError
-s. I would like this value to be either None
, or the numpy array associated with w
.
value = table[w] or table[w.lower()]
# value should be a numpy array, or None
if value is not None:
stack = np.vstack((stack, value))
Only if I go with the above code, and the first lookup is a match, I get :
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
and if I go with value = table[w].any() or table[w.lower()].any()
, then if it's a mismatch, I expectedly bump into :
AttributeError: 'NoneType' object has no attribute 'any'
I must be missing the correct way to do this, how to do ?
In numpy, we can check that whether none of the elements of given array is zero or not with the help of numpy. all() function. In this function pass an array as parameter. If any of one element of the passed array is zero then it returns False otherwise it returns True boolean value.
Using Numpy array, we can easily find whether specific values are present or not. For this purpose, we use the “in” operator. “in” operator is used to check whether certain element and values are present in a given sequence and hence return Boolean values 'True” and “False“.
In Python, NumPy with the latest version where nan is a value only for floating arrays only which stands for not a number and is a numeric data type which is used to represent an undefined value. In Python, NumPy defines NaN as a constant value.
if type(value) is numpy.ndarray:
#do numpy things
else
# Handle None
Though the above would work, I would suggest to keep signatures simple and consistent, ie table[w] should always return numpy array. In case of None, return empty array.
The question is answered, but other folks who encounter this error may want a general solution. With the idea of being explicit in mind we can use the function isinstance. Here is a working example.
import numpy as np
a = np.array([1,2,3])
b = None
for itm in [a,b]:
isinstance(itm,np.ndarray)
So in the context of the question
value = table[w]
if not isinstance(value,np.ndarray):
value = table[w.lower()]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With