George Francis
George Francis

Reputation: 502

Combine multiple numpy arrays together with different types together

I have 2 multidimensional numpy arrays in which the elements inside of them can be of different data types. I want to concatenate these arrays together into one singular array.

Basically I have arrays that look like this:

a = [['A', 4, 0.5], ['B', 2, 1.9], ['F', 5, 2.0]]
b = [['Positive'], ['Negative'], ['Positive']]

Then I would like the combined array to look like this:

c = [['A', 4, 0.5, 'Positive'], ['B', 2, 1.9, 'Negative'], ['F', 5, 2.0, 'Positive']]

I currently have the following code:

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

However, the resulting array converts every element into string, rather than conserving its original type, is there a way to combine these arrays without converting the elements into a string?

Upvotes: 1

Views: 955

Answers (1)

Ivan
Ivan

Reputation: 40708

You could zip the two lists together and loop over it in plain 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']]

You can then convert it to a NumPy object array:

>>> np.array(c, dtype=np.object)
array([['A', 4, 0.5, 'Positive'],
       ['B', 2, 1.9, 'Negative'],
       ['F', 5, 2.0, 'Positive']], dtype=object)

Or a one-liner:

>>> np.array([ai + bi for ai, bi in zip(a, b)], dtype=np.object)

Upvotes: 2

Related Questions