
list转换为array失败的解决方法
在将嵌套列表转换为numpy数组时,可能会遇到错误:"setting an array element with a sequence... the detected shape was (20, 15) + inhomogeneous part."。这通常是由于嵌套列表中子列表长度不一致或数据类型不一致造成的。
要解决此问题,首先排除数据类型不一致的问题。如果所有子列表的数据类型相同,则可能是由于子列表长度不一致。
为了解决这个问题,可以对子列表进行填充,使它们具有相同的长度。以下是解决此问题的 python 代码示例:
import numpy as np
props = [[1, 2, 3, {'a': 1, 'b': 2}],
[4, 5, 6, 7, {'c': 3, 'd': 4}],
[8, 9, 10]]
# 获取每个子列表的长度
lengths = [len(inner_list) for inner_list in props]
# 获取最长的子列表长度
max_length = max(lengths)
# 用 none 填充较短的子列表
padded_props = [inner_list + [none] * (max_length - len(inner_list)) for inner_list in props]
# 转换为 numpy 数组
np_props = np.array(padded_props)
print(np_props)输出:
[[1 2 3 {'a': 1, 'b': 2} None]
[4 5 6 7 {'c': 3, 'd': 4}]
[8 9 10 None None]]以上就是嵌套列表转NumPy数组失败:如何解决"setting an array element with a sequence"错误?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号