python - 如何将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 元组数组?
解决方案
试试这个,以获得标题中提到的元组数组:
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)
推荐阅读
- assembly - 如何管理 JMP CALL POP 例程中的结构?
- javascript - 如何在时钟应用程序中用当前时间自动替换过去的秒/分钟/小时
- python - 从一个大字符串中提取参数值
- javascript - 如何将给定表的整数列显示为从 1 开始到前端用户的自动递增系列?
- python - 从基于类的视图中访问请求对象?需要确定请求是否来自移动设备
- sql-server - SQL Server - sp_rename 后的列无效
- python - 饼图根据字典键大小而变化
- php - PHP:parse_ini_file 在本地工作,但不在服务器上
- python - 基于不同的列值创建带有标签的新列
- vue.js - validate iso date but display locale date when using a date picker component