Home > Software engineering >  How can I perform string concatenation in numpy python
How can I perform string concatenation in numpy python

Time:01-22

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

how can I get this result in python?

c = ['a_baby','b_king']

CodePudding user response:

You can use numpy's add string operation:

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

Result:

['a_baby' 'b_king']

CodePudding user response:

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)

Output:

['a_baby', 'b_king']

CodePudding user response:

With dtype object, you can just add (Try it online!):

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

Or if you really want a list as you've shown:

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