首页 > 解决方案 > 将多个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]))

但是,生成的数组将每个元素转换为字符串,而不是保留其原始类型,有没有办法在不将元素转换为字符串的情况下组合这些数组?

标签: pythonnumpymultidimensional-array

解决方案


您可以将这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)

推荐阅读