将多个 numpy 数组与不同类型组合在一起

时间:2021-01-23 11:10:23

标签: python numpy multidimensional-array

我有 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]))

但是,结果数组将每个元素都转换为字符串,而不是保留其原始类型,有没有办法组合这些数组而不将元素转换为字符串?

1 个答案:

答案 0 :(得分:1)

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