首页 > 解决方案 > 如何将numpy列表数组转换为元组数组

问题描述

我正在尝试将我的列表数组转换为元组数组。

results=

    array([[1.        , 0.0342787 ],
           [0.        , 0.04436508],
           [1.        , 0.09101833 ],
           [0.        , 0.03492954],
           [1.        , 0.06059857]])
    
    results1=np.empty((5,), dtype=object)
    results1[:] = np.array([tuple(i) for i in results])
    results1

我按照此处给出的建议尝试了上述操作,但出现错误ValueError: could not broadcast input array from shape (5,2) into shape (5)

如何从一个 numpy 列表数组创建一个 numpy 元组数组?

标签: pythonarraysnumpy

解决方案


试试这个,以获得标题中提到的元组数组:

import numpy as np
results = np.array([[1.        , 0.0342787 ],
                    [0.        , 0.04436508],
                    [1.        , 0.09101833],
                    [0.        , 0.03492954],
                    [1.        , 0.06059857]])
temp = []
for item in results:
    temp.append(tuple(item))
results1= np.empty(len(temp), dtype=object)
results1[:] = temp
print(results1)
#  array([(1.0, 0.0342787), (0.0, 0.04436508), (1.0, 0.09101833),
#         (0.0, 0.03492954), (1.0, 0.06059857)], dtype=object)

推荐阅读