如何在numpy python中执行字符串连接

aiazj4mn  于 2023-01-26  发布在  Python
关注(0)|答案(3)|浏览(132)
a = np.array(['a','b'])
b = np.array(['baby','king'])

我怎样才能在python中得到这个结果?

c = ['a_baby','b_king']
wgx48brx

wgx48brx1#

可以使用numpy的addstring operation

c = np.char.add(np.char.add(a, '_'), b)
print(c)

结果:

['a_baby' 'b_king']
30byixjq

30byixjq2#

import numpy as np
a = np.array(['a','b'])
b = np.array(['baby','king'])

def concat_arrays(a, b):
    try:
        assert(len(a)==len(b)) #To check if both the arrays are of equal length    
    except:
        print("arrays not equal")
    else:
        c=[]
        for i in range(len(a)):
            c.append(a[i] + "_" + b[i])
        return c

c = concat_arrays(a, b)
print(c)

输出:

['a_baby', 'b_king']
k4aesqcs

k4aesqcs3#

使用dtype对象,您只需添加(在线试用!):

c = a.astype(object) + '_' + b

或者,如果您真的想要一个如图所示的列表:

c = (a.astype(object) + '_' + b).tolist()

相关问题