【问题标题】:How to access items from ndarray with dtype=object如何使用 dtype=object 访问数组中的项目
【发布时间】:2022-01-21 09:06:34
【问题描述】:

如何使用 dtype=object 访问 numpy 数组中的数据?

b = numpy.array({"a":[1,2,3]}, dtype=object)

以下引发IndexError

print(b["a"]) 
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

【问题讨论】:

    标签: python numpy numpy-ndarray


    【解决方案1】:

    由于您将 dict 传递给 numpy.array() 而不将其放入列表中,因此这是一个零维数组。要索引到一个零维数组,您可以使用b.item() 来访问里面的元素。为了完整起见,要访问字典中 "a" 键中的数据,可以使用它。

    >>> b.item()["a"]
    [1, 2, 3]
    

    【讨论】:

    • 谢谢!我查找了numpy.org/doc/stable/reference/arrays.ndarray.html,但没有意识到 item() 方法可以让我访问 0-dim 数组。无法使用方括号或点符号访问它。
    • @AnkitSharma 我相信你也可以通过像b[()]["a"]这样的0元组切片来索引0-dim数组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    相关资源
    最近更新 更多