python - How to convert neatly 1 size numpy array to a scalar? Numpy "asscalar" gives error when input is not a 1 size array. -
i have silly interest in how avoid following error in smart way (possibly using right numpy functions).
in many ocasions need use numpy function find single item. however, item present more once, use indeces function in way in output simple variable (if appears once, either string or float) or array (if mutiple instances).
of course, use len() in boolean check , perform conversion. however, know if there 1 step approach. had tought use asscalar however, function returns , error if input not 1 value array (i had hope return input value unchanged :/). here reproduction of error on second part of code
import numpy np inventory = np.array(['eggs', 'milk', 'ham', 'eggs']) drinks = 'milk' food = 'eggs' index_item_searched = np.where(inventory == drinks) items_instore = np.asscalar(inventory[index_item_searched]) print 'the shop has', items_instore index_item_store = np.where(inventory == food) items_instore = np.asscalar(inventory[index_item_store]) print 'the shop has', items_instore #i want output ['eggs', 'eggs']
thanks patience :)
if understand correctly want print scalar in case of single find in inventory
, while want print array in case of multiple finds, answer "this not nice thing do", , considered poor design. in other words, there's reason why can't done without bit of work: can dangerous if code produces different kinds of results based on semantics.
anyway, one of answers @kindall linked question suggests function
def scalify(l): return l if len(l) > 1 else l[0]
which return list given it, unless list has single element in case returns element. need want.
example:
import numpy np def scalify(l): return l if len(l) > 1 else l[0] def getitems(inventory,itemtype): return inventory[inventory==itemtype] inventory = np.array(['eggs', 'milk', 'ham', 'eggs']) drinks = 'milk' food = 'eggs' print 'the shop has %s' % scalify(getitems(inventory,drinks)) print 'the shop has %s' % scalify(getitems(inventory,food))
output:
the shop has milk shop has ['eggs' 'eggs']
Comments
Post a Comment