[英]How to convert neatly 1 size numpy array to a scalar? Numpy “asscalar” gives error when input is not a 1 size array.
我對如何以一種聰明的方式避免出現以下錯誤(可能使用正確的numpy函數)有這種愚蠢的興趣。
在許多情況下,我需要使用numpy where函數來查找單個項目。 但是,有時此項不止一次出現,我想使用where函數中的索引,其輸出方式將是簡單變量(如果出現一次,則為字符串或浮點數)或數組(如果多實例)。
當然,我可以在布爾檢查中使用len()並執行轉換。 但是,我想知道是否有一步法。 我不得不使用asscalar,但是,如果輸入不是1值數組,此函數將返回並出錯(我曾希望它可以返回輸入值不變的:/)。 這是代碼第二部分中錯誤的再現
import numpy as 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 an output like ['Eggs', 'Eggs']
謝謝你的耐心 :)
如果我正確理解在Inventory
中只有一個查找的情況下要打印標量,而在有多個查找的情況下要打印數組,那么答案是“ 這不是一件好事 ”,並且通常被認為是糟糕的設計。 換句話說,有一個原因為什么不做一點工作就無法完成:如果您的代碼根據語義產生不同種類的結果,則可能很危險。
無論如何, @ kindall對已鏈接問題的答案之一表明有一個功能
def scalify(l):
return l if len(l) > 1 else l[0]
它將返回給定的列表,除非列表具有單個元素,在這種情況下它將返回該元素。 正是您
需要的
。
例:
import numpy as 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)))
輸出:
The shop has Milk
The shop has ['Eggs' 'Eggs']
備查:
從numpy v1.16開始,不推薦使用asscalar
。 請改用np.ndarray.item
。 就像另一個答案所說的那樣,通常只返回一個類型的函數會更好,但是有一些值得注意的API並非如此(例如__getitem__
用於numpy數組甚至列表!)。 所以我建議
from typing import Union, Any
import numpy as np
def maybe_single_item(array: np.ndarray) -> Union[np.ndarray, Any]:
try:
return array.item()
except TypeError:
return array
(Python 3.5以上版本)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.