将两个数组合并为一个吗? (Numpy/Python) [英] Append two arrays together into one? (Numpy/Python)

查看:897
本文介绍了将两个数组合并为一个吗? (Numpy/Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个字符串数组,我正在尝试将其与另一个字符串数组连接在一起,以形成一个完整的单词来进行一些Web解析.例如:`

I currently have an array of strings and I'm trying to join it together with another array of strings to form a complete word to do some web parsing. For example:`

Var1    [A   B    C, .... ....]
Var2    [1   2     3]

其中A和B的长度是可变的,我试图像这样将它们连接在一起:``

where A and B are at a variable length and I'm trying to join them together like:``

`
C  [A+1   A+2   A+3
 B+1    B+2   B+3
C+1     C+2    C+3

这就是我尝试过的

for param in np.nditer(Var2):
List = np.append(np.core.defchararray.add(Var1, Var2))

因此,我试图将它们添加在一起,然后创建列表列表,但这不起作用.任何想法如何做到这一点?

So I'm trying to add them together and then create a list of lists, but this isn't working. any ideas how to do this?

推荐答案

这是您要尝试执行的操作:

Is this what you are trying to do:

In [199]: list1 = ['abc','foo','bar']
In [200]: list2 = list('1234')
In [201]: [[a+b for b in list2] for a in list1]
Out[201]: 
[['abc1', 'abc2', 'abc3', 'abc4'],
 ['foo1', 'foo2', 'foo3', 'foo4'],
 ['bar1', 'bar2', 'bar3', 'bar4']]

使用np.char.add并进行广播的等效方法:

The equivalent using np.char.add and broadcasting:

In [210]: np.char.add(np.array(list1)[:,None], np.array(list2))
Out[210]: 
array([['abc1', 'abc2', 'abc3', 'abc4'],
       ['foo1', 'foo2', 'foo3', 'foo4'],
       ['bar1', 'bar2', 'bar3', 'bar4']], dtype='<U4')

对于这个小例子,列表理解版本更快.

For this small example the list comprehension version is faster.

这篇关于将两个数组合并为一个吗? (Numpy/Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆