Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if variable is None or numpy.array

Tags:

python

numpy

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 ?

like image 400
Nikana Reklawyks Avatar asked Sep 19 '16 07:09

Nikana Reklawyks


People also ask

How can I tell if NumPy array is none?

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.

How do you check if a value is in a NumPy array?

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“.

Is NaN in NumPy?

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.


2 Answers

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.

like image 132
Ayan Guha Avatar answered Oct 01 '22 11:10

Ayan Guha


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()]
like image 26
ajrichards Avatar answered Oct 01 '22 10:10

ajrichards