Oliver Maeng
Oliver Maeng

Reputation: 17

How can I perform string concatenation in numpy python

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

how can I get this result in python?

c = ['a_baby','b_king']

Upvotes: 1

Views: 61

Answers (3)

Kelly Bundy
Kelly Bundy

Reputation: 27629

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()

Upvotes: 0

CrookedNoob
CrookedNoob

Reputation: 100

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']

Upvotes: 0

CryptoFool
CryptoFool

Reputation: 23119

You can use numpy's add string operation:

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

Result:

['a_baby' 'b_king']

Upvotes: 4

Related Questions