Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

python - 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?

question from:https://stackoverflow.com/questions/65858512/combine-multiple-numpy-arrays-together-with-different-types-together

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...