修复 Python 中 NumPy 的 0-D 数组上的迭代错误

Vaibhav Vaibhav 2022年5月18日
修复 Python 中 NumPy 的 0-D 数组上的迭代错误

当迭代在 0 维的可迭代对象上执行时,会出现错误 TypeError: iteration over a 0-d array。在本文中,我们将学习如何修复 Python NumPy 中的 TypeError: iteration over a 0-d array 错误。

如何修复 Python NumPy 中的 TypeError:迭代 0-d 数组错误

以下 Python 代码描述了我们可能遇到此错误的场景。

import numpy as np

data = {
    "AB": 1.01,
    "CD": 2.02,
    "EF": 3.03,
    "GH": 4.04,
    "IJ": 5.05,
}

keys, values = np.array(data.items()).T
print(keys)
print(values)

输出:

Traceback (most recent call last):
  File "<string>", line 11, in <module>
TypeError: iteration over a 0-d array

此错误背后的原因是 data.items() 的数据类型,即 <class 'dict_items'>。为避免此错误,我们必须将其数据类型转换为列表或元组。以下 Python 代码显示了如何使用列表和元组修复此错误。

使用列表的解决方案。

import numpy as np

data = {
    "AB": 1.01,
    "CD": 2.02,
    "EF": 3.03,
    "GH": 4.04,
    "IJ": 5.05,
}
print(type(list(data.items())))
keys, values = np.array(list(data.items())).T
print(keys)
print(values)

输出:

<class 'list'>
['AB' 'CD' 'EF' 'GH' 'IJ']
['1.01' '2.02' '3.03' '4.04' '5.05']

下面是一个使用 tuple 的解决方案。

import numpy as np

data = {
    "AB": 1.01,
    "CD": 2.02,
    "EF": 3.03,
    "GH": 4.04,
    "IJ": 5.05,
}
print(type(tuple(data.items())))
keys, values = np.array(tuple(data.items())).T
print(keys)
print(values)

输出:

<class 'tuple'>
['AB' 'CD' 'EF' 'GH' 'IJ']
['1.01' '2.02' '3.03' '4.04' '5.05']
作者: Vaibhav Vaibhav
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

相关文章 - Python Array

相关文章 - Python Error