简体   繁体   English

在numpy中组合两个不同维度的数组

[英]Combine two arrays with different dimensions in numpy

I'm hoping to combine two arrays...我希望结合两个数组...

a = np.array(["A", "B", "C"])
b = np.array(["1", "2", "3", "4", "5"])

into an array (matrix) similar to this:到一个类似于这个的数组(矩阵):

[["A", "B", "C", "1"]
 ["A", "B", "C", "2"]
 ["A", "B", "C", "3"]
 ["A", "B", "C", "4"]
 ["A", "B", "C", "5"]]

I've tried a for-loop, but it doesn't seem to work.我试过 for 循环,但它似乎不起作用。 I'm new to Python, any help will be appreciated.我是 Python 新手,任何帮助将不胜感激。 Thanks.谢谢。

>>> np.hstack((np.tile(a, (len(b), 1)), b[:, None]))
array([['A', 'B', 'C', '1'],
       ['A', 'B', 'C', '2'],
       ['A', 'B', 'C', '3'],
       ['A', 'B', 'C', '4'],
       ['A', 'B', 'C', '5']], dtype='<U1')

This will do the trick:这将解决问题:

import numpy as np

a = np.array(["A", "B", "C"])
b = np.array(["1", "2", "3", "4", "5"])

c=np.hstack([np.broadcast_to(a, shape=(len(b), len(a))), b.reshape(-1,1)])

Output:输出:

[['A' 'B' 'C' '1']
 ['A' 'B' 'C' '2']
 ['A' 'B' 'C' '3']
 ['A' 'B' 'C' '4']
 ['A' 'B' 'C' '5']]

Perhaps use a Python list comprehension with np.append :也许使用带有np.append的 Python 列表理解

>>> [np.append(a,x) for x in b]
[array(['A', 'B', 'C', '1'],
      dtype='<U1'), array(['A', 'B', 'C', '2'],
      dtype='<U1'), array(['A', 'B', 'C', '3'],
      dtype='<U1'), array(['A', 'B', 'C', '4'],
      dtype='<U1'), array(['A', 'B', 'C', '5'],
      dtype='<U1')]

Depending on what you need, you could wrap that result in np.array :根据您的需要,您可以将结果包装在np.array

>>> np.array([np.append(a,x) for x in b])
array([['A', 'B', 'C', '1'],
       ['A', 'B', 'C', '2'],
       ['A', 'B', 'C', '3'],
       ['A', 'B', 'C', '4'],
       ['A', 'B', 'C', '5']],
      dtype='<U1')

One way of doing it would be:一种方法是:

import numpy as np

a = np.array(["A", "B", "C"])
b = np.array(["1", "2", "3", "4", "5"])

output=[]

for i in list(b):
    a_list=list(a)
    a_list.append(i)
    output.append(a_list)

output=np.asarray(output)

print(output)

Result of this is as desired:其结果如预期:

[['A' 'B' 'C' '1']
 ['A' 'B' 'C' '2']
 ['A' 'B' 'C' '3']
 ['A' 'B' 'C' '4']
 ['A' 'B' 'C' '5']]
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM