python - 将多个numpy数组与不同类型组合在一起
问题描述
我有 2 个多维 numpy 数组,其中的元素可以是不同的数据类型。我想将这些数组连接到一个奇异数组中。
基本上我的数组看起来像这样:
a = [['A', 4, 0.5], ['B', 2, 1.9], ['F', 5, 2.0]]
b = [['Positive'], ['Negative'], ['Positive']]
然后我希望组合数组看起来像这样:
c = [['A', 4, 0.5, 'Positive'], ['B', 2, 1.9, 'Negative'], ['F', 5, 2.0, 'Positive']]
我目前有以下代码:
import numpy as np
from itertools import chain
def combine_instances(X, y):
combined_list = []
for i,val in enumerate(X):
combined_list.append(__chain_together(val, y[0]))
result = np.asarray(combined_list)
return result
def __chain_together(a, b):
return list(chain(*[a,b]))
但是,生成的数组将每个元素转换为字符串,而不是保留其原始类型,有没有办法在不将元素转换为字符串的情况下组合这些数组?
解决方案
您可以将这zip
两个列表放在一起并在普通 Python 中循环:
>>> a = [['A', 4, 0.5], ['B', 2, 1.9], ['F', 5, 2.0]]
>>> b = [['Positive'], ['Negative'], ['Positive']]
>>> c = []
>>> for ai, bi in zip(a, b):
... c.append(ai + bi)
>>> c
[['A', 4, 0.5, 'Positive'],
['B', 2, 1.9, 'Negative'],
['F', 5, 2.0, 'Positive']]
然后,您可以将其转换为 NumPy 对象数组:
>>> np.array(c, dtype=np.object)
array([['A', 4, 0.5, 'Positive'],
['B', 2, 1.9, 'Negative'],
['F', 5, 2.0, 'Positive']], dtype=object)
或单线:
>>> np.array([ai + bi for ai, bi in zip(a, b)], dtype=np.object)
推荐阅读
- python - 在熊猫数据框中通过堆栈获取最大值
- asp.net - Safari 用户访问时在站点之间共享 Windows 身份验证
- testing - Grails 4:如何测试依赖于转换器的代码(如“as JSON”)
- python - 如何使用 Keras 中的训练模型预测输入图像,.h5 保存文件?
- python - 在 Python3 中使用结构记录解析串行数据
- sql-server - 根据输入参数更改 WHERE 子句
- python-3.x - gensim LDA中导致主题重叠的常用词
- javascript - 为什么我收到一个错误说拆分未定义?
- powershell - powershell脚本为每个文件/文件夹提供唯一密码
- linux - Linux 服务器用户详细信息