迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

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

作者:迹忆客 最近更新:2023/02/19 浏览次数:

当迭代在 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']

注: 本文转载自:https://www.delftstack.com/zh/howto/python/typeerror-iteration-over-a-0-d-array/

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便