繁体   English   中英

如何将整齐的1大小的numpy数组转换为标量? 输入不是1大小的数组时,Numpy的“ asscalar”给出错误。

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM