【问题标题】:get a dict out of an ndarray从 ndarray 中获取字典
【发布时间】:2015-07-07 18:31:10
【问题描述】:

如何恢复被转换为numpy ndarraydict

即对于以下示例,我想从test_array 恢复test_dict

>>> test_dict = { 'one' : 1 }
>>> test_array = np.asarray(test_dict)
>>> print repr(test_array)

array({'one': 1}, dtype=object)

这些不起作用:

>>> test[0]
IndexError: 0-d arrays can't be indexed

>>> dict(test)
TypeError: iteration over a 0-d array

>>> test.astype(dict)
array({'one': 1}, dtype=object)      # still in array

【问题讨论】:

    标签: python arrays numpy dictionary


    【解决方案1】:

    “不要那样移动你的手臂。”

    但无论如何,我可能会使用:

    >>> test_array
    array({'one': 1}, dtype=object)
    >>> test_array.item()
    {'one': 1}
    

    或就此而言

    >>> test_array.min()
    {'one': 1}
    >>> test_array.max()
    {'one': 1}
    >>> test_array.take(0)
    {'one': 1}
    >>> test_array.flat[0]
    {'one': 1}
    

    【讨论】:

    • 感谢这工作。关于我的手臂疼痛,从npz 文件中恢复嵌套字典会在数组中生成dict --- 像这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多